IEventreAggregate 的实现原理复现代码

IEventreAggregate 的实现原理复现代码

using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommunityToolkitMvvm.Eventreavate
{

    public class uese
    {

        public void work()
        {
            var rec1 = new StringMessageRecive();
            var rec2 = new NuberMessageRecive(); 
            EventAggregate.Instance.Send(new NuberMessage(42));
            EventAggregate.Instance.Send(new StringMessage("helow diasy"));
        }
    }
    abstract class MRecive
    {
        protected MRecive()
        {
            EventAggregate.Instance.Regist(this, Receive);
        }
        public abstract void Receive(Tmeessage tmeessage);
    }
    class StringMessageRecive:MRecive
    {
         

        //public StringMessageRecive()
        //{
             
        //    EventAggregate.Instance.Regist(this, Revive);
        //}

        public override void Receive(StringMessage tmeessage)
        {
            string str = tmeessage.Message.ToString();
        }

        //private void Revive(StringMessage obj)
        //{
        //    string str = obj.Message.ToString();
        //}
    }

    class NuberMessageRecive : MRecive
    {
         

        //public NuberMessageRecive()
        //{

        //    EventAggregate.Instance.Regist(this, Revive);
        //}
         
        public override void Receive(NuberMessage obj)
        {
            string str = obj.Message.ToString();
        }
    }

    record StringMessage(string Message);
    record  NuberMessage(int  Message); 
    public class EventAggregate
    {


        public static EventAggregate Instance { get; } = new();

        record MessageReciver(object reciveer, Action method);

        private Dictionary> Events = new();
        public void Regist(object revive, Action methord)
        {
            var type = typeof(Tmessage);
            if (!Events.ContainsKey(type))
            {
                Events[type] = new();
            }
            Events[type].Add(new(revive, o => methord((Tmessage)o)));

        }
        public void Send(Tmessage tmessage)
        {
            var type = typeof(Tmessage);
            if (!Events.ContainsKey(type)) return;
            foreach (var rev in Events[type])
            {
                rev.method.Invoke(tmessage);
            }
        }
    }
}
 
   

你可能感兴趣的:(java,servlet,前端,开发语言,asp.net)