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/
網(wǎng)站名稱:CQRS+EventSourcing-創(chuàng)新互聯(lián)
當(dāng)前URL:http://muchs.cn/article16/dchhgg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、App開發(fā)、網(wǎng)站營(yíng)銷、服務(wù)器托管、外貿(mào)建站、軟件開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
網(wǎng)頁(yè)設(shè)計(jì)公司知識(shí)