Skip to content

Instantly share code, notes, and snippets.

@spooky
Last active July 6, 2018 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spooky/eaa2fe6984721fa933816a71b78ccfdd to your computer and use it in GitHub Desktop.
Save spooky/eaa2fe6984721fa933816a71b78ccfdd to your computer and use it in GitHub Desktop.
message builder
using System;
using System.Collections.Generic;
namespace MsgBuilder
{
public partial class Builder<T>
{
internal class Message : Dictionary<string, T>, IMessage<T>
{
private Builder<T> _builder;
public IDictionary<string, T> Data => this;
public Message(Builder<T> builder, IDictionary<string, T> values)
{
_builder = builder;
foreach (var item in values)
{
Add(item.Key, item.Value);
}
}
public void Send()
{
_builder._dependency.Use(this);
}
}
private Dependency _dependency;
private Dictionary<string, T> _data;
public Builder(Dependency s)
{
_dependency = s;
}
public Builder<T> Add(string key, T value)
{
if (_data == null)
_data = new Dictionary<string, T>();
_data.Add(key, value);
return this;
}
public IMessage<T> Build()
{
var msg = new Message(this, _data);
_data = null;
return msg;
}
}
}
namespace MsgBuilder
{
public class Client
{
public void Run()
{
var b = new Builder<int>(new Dependency());
b.Add("one", 1)
.Add("two", 2)
.Build()
.Send();
}
}
}
namespace MsgBuilder
{
public class Dependency
{
public void Use<T>(IMessage<T> message)
{
}
}
}
using System.Collections.Generic;
namespace MsgBuilder
{
public interface IMessage<T>
{
IDictionary<string, T> Data { get; }
void Send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment