• 设计模式14-中介者模式


    中介者模式:用一个中介对象来封装一系列的对象交互。使各对象不需要显式地相互引用,从而使耦合松散,而且可以独立改变它们之间的交互(中介)。

     1 namespace DesignModel.中介模式
     2 {
     3     /// <summary>
     4     /// 抽象中介者
     5     /// </summary>
     6     abstract class Mediator
     7     {
     8         public BigGuy bigguy { get; set; }
     9         public HiMan himan { get; set; }
    10         public abstract void Send(string msg, Body body);
    11     }
    12     /// <summary>
    13     /// 前台类(通过前台找到公司其他同事)
    14     /// </summary>
    15     class QianTai : Mediator
    16     {
    17 
    18         public override void Send(string msg, Body body)
    19         {
    20             if (typeof(Body) == typeof(BigGuy))
    21             {
    22                 himan.Recive(msg);
    23             }
    24             else
    25             {
    26                 bigguy.Recive(msg);
    27             }
    28         }
    29     }
    30 
    31     abstract class Body
    32     {
    33         protected Mediator med;
    34         public Body(Mediator mediator)
    35         {
    36             med = mediator;
    37         }
    38     }
    39     class BigGuy : Body
    40     {
    41         public BigGuy(Mediator med) : base(med) { }
    42         public void Send(string msg)
    43         {
    44             med.Send("", this);
    45         }
    46         public void Recive(string msg)
    47         {
    48             Console.WriteLine(msg);
    49         }
    50     }
    51     class HiMan : Body
    52     {
    53         public HiMan(Mediator med) : base(med) { }
    54         public void Send(string msg)
    55         {
    56             med.Send("", this);
    57         }
    58         public void Recive(string msg)
    59         {
    60             Console.WriteLine(msg);
    61         }
    62     }
    63 
    64 }
    65 
    66 
    67   static void 中介模式()
    68         {
    69             Mediator qiantai = new QianTai();
    70             BigGuy bigguy = new BigGuy(qiantai);//同事需要认识前台
    71             HiMan himan = new HiMan(qiantai);
    72             qiantai.bigguy = bigguy;//前台需要认识同事
    73             qiantai.himan = himan;
    74 
    75             bigguy.Send("hi, who can fuck me?");
    76             himan.Send("hi,bigguy,bu yao xiao zhang");
    77         }
    View Code

    结构上需要注意的是,中介者将具体同事类做为了属性,注意使用时让中介(前台)“认识”(获得依赖)所有同事,让同事都"认识"(获得依赖)中介(前台)。

    缺点:随意具体对象数量多到一定程序,中介对象的业务将会变得更加复杂而不好维护。

  • 相关阅读:
    LC.225. Implement Stack using Queues(using two queues)
    LC.232. Implement Queue using Stacks(use two stacks)
    sort numbers with two stacks(many duplicates)
    LC.154. Find Minimum in Rotated Sorted Array II
    LC.81. Search in Rotated Sorted Array II
    LC.35.Search Insert Position
    前后端分离:(一)
    Redis基本使用(一)
    GIT篇章(二)
    GIT篇章(一)
  • 原文地址:https://www.cnblogs.com/liurui/p/5565157.html
Copyright © 2020-2023  润新知