• 设计模式


    使用中介模式,大家通过往中介发消息,和从中介接受消息。从而避免了多个端之间的耦合。就像你看房,你不需要联系各个房东,你只需要联系中介,由中介去联系各个房东和各个租客。

    abstract class Mediator
    {
        public abstract void Send(string message, Colleague colleague);
    }
    
    abstract class Colleague
    {
        protected Mediator mediator;
    
        public Colleague(Mediator mediator)
        {
            this.mediator = mediator;
        }
    
        public abstract void Notify(string message);
    }
    
    class ConcreteColleague : Colleague
    {        
        public string Name { get; set; }
     
        public ConcreteColleague(Mediator mediator) : base(mediator) { }
    
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
    
        public override void Notify(string message)
        {
            Console.WriteLine(string.Format("{0}收到消息:{1}", Name, message));
        }
    }
    
    class ConcreteMediator : Mediator
    {
        IList<Colleague> _colleagueList = new List<Colleague>();
    
        public void AddColleague(Colleague colleague)
        {
            _colleagueList.Add(colleague);
        }
    
        public void RemoveColleague(Colleague colleague)
        {
            _colleagueList.Remove(colleague);
        }
    
        public override void Send(string message, Colleague colleague)
        {
            foreach (Colleague coll in _colleagueList)
            {
                if (coll == colleague) continue;
    
                coll.Notify(message);
            }
        }
    }
    
    ConcreteMediator ccm = new ConcreteMediator();
    ConcreteColleague ccA = new ConcreteColleague(ccm);
    ccA.Name = "中国";
    
    ConcreteColleague ccB = new ConcreteColleague(ccm);
    ccB.Name = "巴基斯坦";
    
    ConcreteColleague ccC = new ConcreteColleague(ccm);
    ccC.Name = "孟加拉国";
    
    ccm.AddColleague(ccA);
    ccm.AddColleague(ccB);
    ccm.AddColleague(ccC);
    
    ccA.Send("我们是好朋友啊");
    
    巴基斯坦收到消息:我们是好朋友啊
    孟加拉国收到消息:我们是好朋友啊
    
  • 相关阅读:
    开启防火墙如何部署k8s
    docker及k8s安装consul
    docker安装rocketmq
    docker安装gitlab
    k8s认证与授权
    部署dashboard
    k8sStatefulSet控制器
    k8sSecret资源
    k8sConfigMap资源
    使用nfs制作动态分配存储卷
  • 原文地址:https://www.cnblogs.com/MichaelLoveSna/p/14199180.html
Copyright © 2020-2023  润新知