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();
}
}
}
下面是原視頻:https://www.bilibili.com/video/BV1HK411L7Lq/
創新互聯公司專注于石棉網站建設服務及定制,我們擁有豐富的企業做網站經驗。 熱誠為您提供石棉營銷型網站建設,石棉網站制作、石棉網頁設計、石棉網站官網定制、小程序制作服務,打造石棉網絡公司原創品牌,更為您提供石棉網站排名全網營銷落地服務。
網站名稱:CQRS+EventSourcing-創新互聯
當前URL:http://m.newbst.com/article16/dchhgg.html
成都網站建設公司_創新互聯,為您提供自適應網站、App開發、網站營銷、服務器托管、外貿建站、軟件開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯