DDD 初探一

DDD是领域驱动设计(DDD:Domain-Driven Design)的简称,是一套综合软件系统分析和设计的面向对象建模方法。

领域驱动设计是从业务出发,将业务划分为不同领域。

实现demo。主要是事件的订阅,取消订阅以及发布。

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace LibEventBus
{
    /// <summary>
    /// 发布与订阅逻辑处理
    /// </summary>
    public class EventBusHelper
    {
        private static EventBusHelper _eventBusHelper;
        static object intanceObject = new object();
        private object sync;
        private Dictionary<EEventBusType, List<IEventHandler>> subscribeList;
        private Dictionary<EEventBusType, Queue<EventBusSource>> publishList;

        /// <summary>
        /// 构造函数
        /// </summary>
        private EventBusHelper()
        {
            sync = new object();
            subscribeList = new Dictionary<EEventBusType, List<IEventHandler>>();
            publishList = new Dictionary<EEventBusType, Queue<EventBusSource>>();
            Start();
        }

        /// <summary>
        /// 单例模式
        /// </summary>
        public static EventBusHelper Instance
        {
            get
            {
                if (_eventBusHelper == null)
                {
                    lock(intanceObject)
                    {
                        if (_eventBusHelper == null)
                            _eventBusHelper = new EventBusHelper();
                    }
                }

                return _eventBusHelper;
            }
        }

        /// <summary>
        /// 订阅事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="eventHandler"></param>
        public void Subscribe(EEventBusType type, IEventHandler eventHandler)
        {
            lock (sync)
            {
                if (!subscribeList.ContainsKey(type))
                {
                    subscribeList[type] = new List<IEventHandler>();
                }

                List<IEventHandler> eventHandlerList = subscribeList[type];
                if (eventHandlerList.IndexOf(eventHandler) < 0)
                    eventHandlerList.Add(eventHandler);
                else
                    throw new Exception(string.Format("已经订阅该事件 {0}", type.ToString()));
            }
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="type"></param>
        public void Unsubscribe(EEventBusType type)
        {
            lock (sync)
            {
                if (subscribeList.ContainsKey(type))
                    subscribeList.Remove(type);
            }
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="type"></param>
        /// <param name="handler"></param>
        public void Unsubscribe(EEventBusType type, IEventHandler handler)
        {
            lock (sync)
            {
                if (subscribeList.ContainsKey(type) && subscribeList[type].IndexOf(handler) >= 0)
                    subscribeList[type].Remove(handler);
            }
        }

        /// <summary>
        /// 发布事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="e"></param>
        /// <param name="callback"></param>
        public void Publish(EEventBusType type, IEvent e,
            Action<IEvent, bool, Exception> callback)
        {
            lock (sync)
            {
                if (!publishList.ContainsKey(type))
                    publishList[type] = new Queue<EventBusSource>();

                Queue<EventBusSource> queue = publishList[type];
                EventBusSource item = new EventBusSource(e, callback);
                queue.Enqueue(item);
            }
        }

        private void EventBusLoop()
        {
            while(true)
            {
                if (publishList == null || publishList.Count == 0)
                {
                    Thread.Sleep(500);
                    continue;
                }

                lock(sync)
                {
                    EventBusWorkAsync();
                }
                Thread.Sleep(10);
            }
        }

        private void EventBusWork()
        {
            foreach (var item in publishList)
            {
                if (!subscribeList.ContainsKey(item.Key) || subscribeList[item.Key].Count == 0)
                    continue;

                Queue<EventBusSource> queueList = item.Value;
                // 循环执行事件源事件
                int count = queueList.Count;
                for (int i = 0; i < count; ++i)
                {
                    EventBusSource e = queueList.Dequeue();
                    EventRun(subscribeList[item.Key], e);
                }
            }
        }

        private void EventBusWorkAsync()
        {
            foreach (var item in publishList)
            {
                if (!subscribeList.ContainsKey(item.Key) || subscribeList[item.Key].Count == 0)
                    continue;

                Queue<EventBusSource> queueList = item.Value;
                // 循环执行事件源事件
                int count = queueList.Count;
                for (int i = 0; i < count; ++i)
                {
                    EventBusSource e = queueList.Dequeue();
                    new TaskFactory().StartNew(()=>
                    {
                        EventRun(subscribeList[item.Key], e);
                    });
                }
            }
        }

        private void EventRun(List<IEventHandler> handlerList, EventBusSource e)
        {
            foreach (var eventHandler in handlerList)
            {
                try
                {
                    if (eventHandler != null)
                        eventHandler.Handle(e.Event);
                    if (e != null && e.Callback != null)
                        e.Callback(e.Event, true, null);
                }
                catch (Exception ex)
                {
                    if (e != null && e.Callback != null)
                        e.Callback(e.Event, false, ex);
                }
            }
        }

        private void Start()
        {
            Thread loopThread = new Thread(EventBusLoop);
            loopThread.IsBackground = true;
            loopThread.Start();
        }

        class EventBusSource
        {
            public IEvent Event;
            public Action<IEvent, bool, Exception> Callback;

            public EventBusSource(IEvent e,
            Action<IEvent, bool, Exception> callback)
            {
                Event = e;
                Callback = callback;
            }
        }

    }
}
原文地址:https://www.cnblogs.com/qianyindichang/p/8182797.html