using System; using System.Collections.Generic; using System.Linq; namespace CQRS { public class EventBroker { public List<Event> AllEvents = new List<Event>(); public EventHandler<Command> Commands; public EventHandler<Query> Queries; public void Command(Command cmd) { Commands.Invoke(this, cmd); } public T Query<T>(Query q) { Queries.Invoke(this, q); return (T)q.Result; } } public class Event { } public class Command : EventArgs { } public class Query { public object Result; } public class Person { private int age; EventBroker eventBroker; public Person(EventBroker eventBroker) { var self = this; this.eventBroker = eventBroker; this.eventBroker.Commands += (object sender, Command cmd) => { var c = cmd as AgeChangedCommand; eventBroker.AllEvents.Add(new AgeChangedEvent(self, self.age, c.Age)); self.age = c.Age; }; this.eventBroker.Queries += (object sender, Query query) => { var q = query as AgeQuery; q.Result = self.age; }; } } public class AgeChangedEvent : Event { public Person Target; public int oldValue; public int newValue; public AgeChangedEvent(Person target, int oldVal, int newVal) { Target = target; oldValue = oldVal; newValue = newVal; } public override string ToString() { return $"Age changed from {oldValue} to {newValue}"; } } public class AgeChangedCommand : Command { public Person Target; public int Age; public AgeChangedCommand(Person p, int age) { Target = p; Age = age; } } public class AgeQuery : Query { public Person Target; public AgeQuery(Person p) { Target = p; } } class Program { static void Main(string[] args) { EventBroker eb = new EventBroker(); Person p = new Person(eb); //command eb.Command(new AgeChangedCommand(p, 18)); eb.Command(new AgeChangedCommand(p, 30)); //event list foreach (var ev in eb.AllEvents) { Console.WriteLine(ev.ToString()); } //query var res = eb.Query<int>(new AgeQuery(p)); Console.WriteLine(res); Console.ReadKey(); } } }
下面是原视频: