中介者模式(Mediator Pattern)

设计模式 - 吕震宇

.NET设计模式系列文章

薛敬明的专栏

乐在其中设计模式(C#)


乐在其中设计模式(C#) - 中介者模式(Mediator Pattern)

乐在其中设计模式(C#) - 中介者模式(Mediator Pattern)


作者: webabcd


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


示例
有一个Message实体类,某个对象对它的操作有Send()和Insert()方法,现在用一个中介对象来封装这一系列的对象交互。



MessageModel
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.Mediator
{
    
/// <summary>
    
/// Message实体类
    
/// </summary>

    public class MessageModel
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="msg">Message内容</param>
        
/// <param name="pt">Message发布时间</param>

        public MessageModel(string msg, DateTime pt)
        
{
            
this._message = msg;
            
this._publishTime = pt;
        }


        
private string _message;
        
/// <summary>
        
/// Message内容
        
/// </summary>

        public string Message
        
{
            
get return _message; }
            
set { _message = value; }
        }


        
private DateTime _publishTime;
        
/// <summary>
        
/// Message发布时间
        
/// </summary>

        public DateTime PublishTime
        
{
            
get return _publishTime; }
            
set { _publishTime = value; }
        }

    }

}


AbstractMessageMediator
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.Mediator
{
    
/// <summary>
    
/// 抽象中介者(Mediator)
    
/// </summary>

    public abstract class AbstractMessageMediator
    
{
        
/// <summary>
        
/// 注册一个操作Message的对象
        
/// </summary>
        
/// <param name="AbstractMessage">AbstractMessage</param>

        public abstract void Register(AbstractMessage AbstractMessage);

        
/// <summary>
        
/// 发送Message
        
/// </summary>
        
/// <param name="from">来自UserId</param>
        
/// <param name="to">发送到UserId</param>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public abstract string Send(string from, string to, MessageModel mm);
    }

}


MessageMediator
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.Mediator
{
    
/// <summary>
    
/// 中介者(ConcreteMediator)
    
/// </summary>

    public class MessageMediator : AbstractMessageMediator
    
{
        
private Dictionary<string, AbstractMessage> _dictionary = new Dictionary<string, AbstractMessage>();

        
/// <summary>
        
/// 注册一个操作Message的对象
        
/// </summary>
        
/// <param name="abstractMessage">AbstractMessage</param>

        public override void Register(AbstractMessage abstractMessage)
        
{
            
if (!_dictionary.ContainsKey(abstractMessage.UserId))
            
{
                _dictionary.Add(abstractMessage.UserId, abstractMessage);
            }


            abstractMessage.AbstractMessageMediator 
= this;
        }


        
/// <summary>
        
/// 发送Message
        
/// </summary>
        
/// <param name="from">来自UserId</param>
        
/// <param name="to">发送到UserId</param>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public override string Send(string from, string to, MessageModel mm)
        
{
            AbstractMessage abstractMessage 
= _dictionary[to];
            
if (abstractMessage != null)
            
{
                
return abstractMessage.Insert(from, mm);
            }

            
else
            
{
                
return null;
            }

        }

    }

}


AbstractMessage
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.Mediator
{
    
/// <summary>
    
/// 操作Message抽象类(Colleague)
    
/// </summary>

    public abstract class AbstractMessage
    
{
        
private AbstractMessageMediator _abstractMessageMediator;
        
private string _userId;

        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="userId">UserId</param>

        public AbstractMessage(string userId)
        
{
            
this._userId = userId;
        }


        
/// <summary>
        
/// UserId
        
/// </summary>

        public string UserId
        
{
            
get return _userId; }
        }


        
/// <summary>
        
/// 中介者
        
/// </summary>

        public AbstractMessageMediator AbstractMessageMediator
        
{
            
get return _abstractMessageMediator; }
            
set { _abstractMessageMediator = value; }
        }


        
/// <summary>
        
/// 发送Message(由客户端调用)
        
/// </summary>
        
/// <param name="to">发送到UserId</param>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public string Send(string to, MessageModel mm)
        
{
            
return _abstractMessageMediator.Send(_userId, to, mm);
        }


        
/// <summary>
        
/// 接受Message(由中介者调用)
        
/// </summary>
        
/// <param name="from">来自UserId</param>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public abstract string Insert(string from, MessageModel mm);
    }

}


SqlMessage
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.Mediator
{
    
/// <summary>
    
/// Sql方式操作Message(ConcreteColleague)
    
/// </summary>

    public class SqlMessage : AbstractMessage
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="userId">UserId</param>

        public SqlMessage(string userId)
            : 
base(userId)
        
{

        }


        
/// <summary>
        
/// 接受Message(由中介者调用)
        
/// </summary>
        
/// <param name="from">来自UserId</param>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public override string Insert(string from, MessageModel mm)
        
{
            
return "Sql方式插入Message(" + from + "发送给" + base.UserId + ""
                
+ " - 内容:" + mm.Message
                
+ " - 时间:" + mm.PublishTime.ToString();
        }

    }

}


XmlMessage
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  Pattern.Mediator
{
    
/// <summary>
    
/// Xml方式操作Message(ConcreteColleague)
    
/// </summary>

    public class XmlMessage : AbstractMessage
    
{
        
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="userId">UserId</param>

        public XmlMessage(string userId)
            : 
base(userId)
        
{

        }


        
/// <summary>
        
/// 接受Message(由中介者调用)
        
/// </summary>
        
/// <param name="from">来自UserId</param>
        
/// <param name="mm">Message实体对象</param>
        
/// <returns></returns>

        public override string Insert(string from, MessageModel mm)
        
{
            
return "Xml方式插入Message(" + from + "发送给" + base.UserId + ""
                
+ " - 内容:" + mm.Message
                
+ " - 时间:" + mm.PublishTime.ToString();
        }

    }

}



Test
using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

using  Pattern.Mediator;

public  partial  class  Mediator : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        AbstractMessageMediator messageMediator 
= new MessageMediator();

        AbstractMessage user1 
= new SqlMessage("user1");
        AbstractMessage user2 
= new SqlMessage("user2");
        AbstractMessage user3 
= new XmlMessage("user3");
        AbstractMessage user4 
= new XmlMessage("user4");

        messageMediator.Register(user1);
        messageMediator.Register(user2);
        messageMediator.Register(user3);
        messageMediator.Register(user4);

        Response.Write(user1.Send(
"user2"new MessageModel("你好!", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(user2.Send(
"user1"new MessageModel("我不好!", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(user1.Send(
"user2"new MessageModel("不好就不好吧。", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(user3.Send(
"user4"new MessageModel("吃了吗?", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(user4.Send(
"user3"new MessageModel("没吃,你请我?", DateTime.Now)));
        Response.Write(
"<br />");
        Response.Write(user3.Send(
"user4"new MessageModel("不请。", DateTime.Now)));
        Response.Write(
"<br />");
    }

}


运行结果
Sql方式插入Message(user1发送给user2) - 内容:你好! - 时间:2007-5-19 23:43:19
Sql方式插入Message(user2发送给user1) - 内容:我不好! - 时间:2007-5-19 23:43:19
Sql方式插入Message(user1发送给user2) - 内容:不好就不好吧。 - 时间:2007-5-19 23:43:19
Xml方式插入Message(user3发送给user4) - 内容:吃了吗? - 时间:2007-5-19 23:43:19
Xml方式插入Message(user4发送给user3) - 内容:没吃,你请我? - 时间:2007-5-19 23:43:19
Xml方式插入Message(user3发送给user4) - 内容:不请。 - 时间:2007-5-19 23:43:19


参考
http://www.dofactory.com/Patterns/PatternMediator.aspx


OK
[源码下载]

设计模式22:Mediator Pattern (调解者模式)

英文原文:http://www.dofactory.com/Patterns/PatternMediator.aspx

一、Mediator Pattern (调解者模式)的定义

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

定义一个对象将一系列对象如何相互作用的操作进行封装。调解者通过避免一个对象明确指向其余的对象来促使自由耦合,同时能够让你单独的改变他们之间的相互作用。

二、UML类图

Median

  • Mediator  (IChatroom)
    • 定义一个接口用于与同事级对象进行通信
  • ConcreteMediator  (Chatroom)
    • 通过与同事级对象进行对等来实现相互协作行为
    • 知道并且维持本身的同事级对象
  • Colleague classes  (Participant)
    • 每个同事级对象都知道自己的调节者对象
    • 每个同事级对象在与另外的同事级对象进行通信时必须要与调节者进行通信。

    三、调解者模式实例代码

    [c-sharp] view plain copy
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace Mediator_Pattern  
    7. {  
    8.     /// <summary>  
    9.   
    10.     /// MainApp startup class for Structural   
    11.   
    12.     /// Mediator Design Pattern.  
    13.   
    14.     /// </summary>  
    15.   
    16.     class MainApp  
    17.     {  
    18.   
    19.         /// <summary>  
    20.   
    21.         /// Entry point into console application.  
    22.   
    23.         /// </summary>  
    24.   
    25.         static void Main()  
    26.         {  
    27.   
    28.             ConcreteMediator m = new ConcreteMediator();  
    29.   
    30.   
    31.   
    32.             ConcreteColleague1 c1 = new ConcreteColleague1(m);  
    33.   
    34.             ConcreteColleague2 c2 = new ConcreteColleague2(m);  
    35.   
    36.   
    37.   
    38.             m.Colleague1 = c1;  
    39.   
    40.             m.Colleague2 = c2;  
    41.   
    42.   
    43.   
    44.             c1.Send("How are you?");  
    45.   
    46.             c2.Send("Fine, thanks");  
    47.   
    48.   
    49.   
    50.             // Wait for user  
    51.   
    52.             Console.ReadKey();  
    53.   
    54.         }  
    55.   
    56.     }  
    57.   
    58.   
    59.   
    60.     /// <summary>  
    61.   
    62.     /// The 'Mediator' abstract class  
    63.   
    64.     /// </summary>  
    65.   
    66.     abstract class Mediator  
    67.     {  
    68.   
    69.         public abstract void Send(string message,  
    70.   
    71.           Colleague colleague);  
    72.   
    73.     }  
    74.   
    75.   
    76.   
    77.     /// <summary>  
    78.   
    79.     /// The 'ConcreteMediator' class  
    80.   
    81.     /// </summary>  
    82.   
    83.     class ConcreteMediator : Mediator  
    84.     {  
    85.   
    86.         private ConcreteColleague1 _colleague1;  
    87.   
    88.         private ConcreteColleague2 _colleague2;  
    89.   
    90.   
    91.   
    92.         public ConcreteColleague1 Colleague1  
    93.         {  
    94.   
    95.             set { _colleague1 = value; }  
    96.   
    97.         }  
    98.   
    99.   
    100.   
    101.         public ConcreteColleague2 Colleague2  
    102.         {  
    103.   
    104.             set { _colleague2 = value; }  
    105.   
    106.         }  
    107.   
    108.   
    109.   
    110.         public override void Send(string message,  
    111.   
    112.           Colleague colleague)  
    113.         {  
    114.   
    115.             if (colleague == _colleague1)  
    116.             {  
    117.   
    118.                 _colleague2.Notify(message);  
    119.   
    120.             }  
    121.   
    122.             else  
    123.             {  
    124.   
    125.                 _colleague1.Notify(message);  
    126.   
    127.             }  
    128.   
    129.         }  
    130.   
    131.     }  
    132.   
    133.   
    134.   
    135.     /// <summary>  
    136.   
    137.     /// The 'Colleague' abstract class  
    138.   
    139.     /// </summary>  
    140.   
    141.     abstract class Colleague  
    142.     {  
    143.   
    144.         protected Mediator mediator;  
    145.   
    146.   
    147.   
    148.         // Constructor  
    149.   
    150.         public Colleague(Mediator mediator)  
    151.         {  
    152.   
    153.             this.mediator = mediator;  
    154.   
    155.         }  
    156.   
    157.     }  
    158.   
    159.   
    160.   
    161.     /// <summary>  
    162.   
    163.     /// A 'ConcreteColleague' class  
    164.   
    165.     /// </summary>  
    166.   
    167.     class ConcreteColleague1 : Colleague  
    168.     {  
    169.   
    170.         // Constructor  
    171.   
    172.         public ConcreteColleague1(Mediator mediator)  
    173.   
    174.             : base(mediator)  
    175.         {  
    176.   
    177.         }  
    178.   
    179.   
    180.   
    181.         public void Send(string message)  
    182.         {  
    183.   
    184.             mediator.Send(message, this);  
    185.   
    186.         }  
    187.   
    188.   
    189.   
    190.         public void Notify(string message)  
    191.         {  
    192.   
    193.             Console.WriteLine("Colleague1 gets message: "  
    194.   
    195.               + message);  
    196.   
    197.         }  
    198.   
    199.     }  
    200.   
    201.   
    202.   
    203.     /// <summary>  
    204.   
    205.     /// A 'ConcreteColleague' class  
    206.   
    207.     /// </summary>  
    208.   
    209.     class ConcreteColleague2 : Colleague  
    210.     {  
    211.   
    212.         // Constructor  
    213.   
    214.         public ConcreteColleague2(Mediator mediator)  
    215.   
    216.             : base(mediator)  
    217.         {  
    218.   
    219.         }  
    220.   
    221.   
    222.   
    223.         public void Send(string message)  
    224.         {  
    225.   
    226.             mediator.Send(message, this);  
    227.   
    228.         }  
    229.   
    230.   
    231.   
    232.         public void Notify(string message)  
    233.         {  
    234.   
    235.             Console.WriteLine("Colleague2 gets message: "  
    236.   
    237.               + message);  
    238.   
    239.         }  
    240.   
    241.     }  
    242. }  

    四、另外一个使用调解者模式的实例代码

    This real-world code demonstrates the Mediator pattern facilitating loosely coupled communication between different Participants registering with a Chatroom. The Chatroom is the central hub through which all communication takes place. At this point only one-to-one communication is implemented in the Chatroom, but would be trivial to change to one-to-many.

    [c-sharp] view plain copy
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace Mediator_Pattern  
    7. {  
    8.     /// <summary>  
    9.   
    10.     /// MainApp startup class for Real-World   
    11.   
    12.     /// Mediator Design Pattern.  
    13.   
    14.     /// </summary>  
    15.   
    16.     class MainApp  
    17.     {  
    18.   
    19.         /// <summary>  
    20.   
    21.         /// Entry point into console application.  
    22.   
    23.         /// </summary>  
    24.   
    25.         static void Main()  
    26.         {  
    27.   
    28.             // Create chatroom  
    29.   
    30.             Chatroom chatroom = new Chatroom();  
    31.   
    32.   
    33.   
    34.             // Create participants and register them  
    35.   
    36.             Participant George = new Beatle("George");  
    37.   
    38.             Participant Paul = new Beatle("Paul");  
    39.   
    40.             Participant Ringo = new Beatle("Ringo");  
    41.   
    42.             Participant John = new Beatle("John");  
    43.   
    44.             Participant Yoko = new NonBeatle("Yoko");  
    45.   
    46.   
    47.   
    48.             chatroom.Register(George);  
    49.   
    50.             chatroom.Register(Paul);  
    51.   
    52.             chatroom.Register(Ringo);  
    53.   
    54.             chatroom.Register(John);  
    55.   
    56.             chatroom.Register(Yoko);  
    57.   
    58.   
    59.   
    60.             // Chatting participants  
    61.   
    62.             Yoko.Send("John""Hi John!");  
    63.   
    64.             Paul.Send("Ringo""All you need is love");  
    65.   
    66.             Ringo.Send("George""My sweet Lord");  
    67.   
    68.             Paul.Send("John""Can't buy me love");  
    69.   
    70.             John.Send("Yoko""My sweet love");  
    71.   
    72.   
    73.   
    74.             // Wait for user  
    75.   
    76.             Console.ReadKey();  
    77.   
    78.         }  
    79.   
    80.     }  
    81.   
    82.   
    83.   
    84.     /// <summary>  
    85.   
    86.     /// The 'Mediator' abstract class  
    87.   
    88.     /// </summary>  
    89.   
    90.     abstract class AbstractChatroom  
    91.     {  
    92.   
    93.         public abstract void Register(Participant participant);  
    94.   
    95.         public abstract void Send(  
    96.   
    97.           string from, string to, string message);  
    98.   
    99.     }  
    100.   
    101.   
    102.   
    103.     /// <summary>  
    104.   
    105.     /// The 'ConcreteMediator' class  
    106.   
    107.     /// </summary>  
    108.   
    109.     class Chatroom : AbstractChatroom  
    110.     {  
    111.   
    112.         private Dictionary<string, Participant> _participants =  
    113.   
    114.           new Dictionary<string, Participant>();  
    115.   
    116.   
    117.   
    118.         public override void Register(Participant participant)  
    119.         {  
    120.   
    121.             if (!_participants.ContainsValue(participant))  
    122.             {  
    123.   
    124.                 _participants[participant.Name] = participant;  
    125.   
    126.             }  
    127.   
    128.   
    129.   
    130.             participant.Chatroom = this;  
    131.   
    132.         }  
    133.   
    134.   
    135.   
    136.         public override void Send(  
    137.   
    138.           string from, string to, string message)  
    139.         {  
    140.   
    141.             Participant participant = _participants[to];  
    142.   
    143.   
    144.   
    145.             if (participant != null)  
    146.             {  
    147.   
    148.                 participant.Receive(from, message);  
    149.   
    150.             }  
    151.   
    152.         }  
    153.   
    154.     }  
    155.   
    156.   
    157.   
    158.     /// <summary>  
    159.   
    160.     /// The 'AbstractColleague' class  
    161.   
    162.     /// </summary>  
    163.   
    164.     class Participant  
    165.     {  
    166.   
    167.         private Chatroom _chatroom;  
    168.   
    169.         private string _name;  
    170.   
    171.   
    172.   
    173.         // Constructor  
    174.   
    175.         public Participant(string name)  
    176.         {  
    177.   
    178.             this._name = name;  
    179.   
    180.         }  
    181.   
    182.   
    183.   
    184.         // Gets participant name  
    185.   
    186.         public string Name  
    187.         {  
    188.   
    189.             get { return _name; }  
    190.   
    191.         }  
    192.   
    193.   
    194.   
    195.         // Gets chatroom  
    196.   
    197.         public Chatroom Chatroom  
    198.         {  
    199.   
    200.             set { _chatroom = value; }  
    201.   
    202.             get { return _chatroom; }  
    203.   
    204.         }  
    205.   
    206.   
    207.   
    208.         // Sends message to given participant  
    209.   
    210.         public void Send(string to, string message)  
    211.         {  
    212.   
    213.             _chatroom.Send(_name, to, message);  
    214.   
    215.         }  
    216.   
    217.   
    218.   
    219.         // Receives message from given participant  
    220.   
    221.         public virtual void Receive(  
    222.   
    223.           string from, string message)  
    224.         {  
    225.   
    226.             Console.WriteLine("{0} to {1}: '{2}'",  
    227.   
    228.               from, Name, message);  
    229.   
    230.         }  
    231.   
    232.     }  
    233.   
    234.   
    235.   
    236.     /// <summary>  
    237.   
    238.     /// A 'ConcreteColleague' class  
    239.   
    240.     /// </summary>  
    241.   
    242.     class Beatle : Participant  
    243.     {  
    244.   
    245.         // Constructor  
    246.   
    247.         public Beatle(string name)  
    248.   
    249.             : base(name)  
    250.         {  
    251.   
    252.         }  
    253.   
    254.   
    255.   
    256.         public override void Receive(string from, string message)  
    257.         {  
    258.   
    259.             Console.Write("To a Beatle: ");  
    260.   
    261.             base.Receive(from, message);  
    262.   
    263.         }  
    264.   
    265.     }  
    266.   
    267.   
    268.   
    269.     /// <summary>  
    270.   
    271.     /// A 'ConcreteColleague' class  
    272.   
    273.     /// </summary>  
    274.   
    275.     class NonBeatle : Participant  
    276.     {  
    277.   
    278.         // Constructor  
    279.   
    280.         public NonBeatle(string name)  
    281.   
    282.             : base(name)  
    283.         {  
    284.   
    285.         }  
    286.   
    287.   
    288.   
    289.         public override void Receive(string from, string message)  
    290.         {  
    291.   
    292.             Console.Write("To a non-Beatle: ");  
    293.   
    294.             base.Receive(from, message);  
    295.   
    296.         }  
    297.   
    298.     }  
    299. }  

    四.中介者模式案例分析(Example

    1、场景

    实现一个聊天室功能,聊城室就是一个中介者,参与聊天的人就是同事对象,如下图所示

    AbstractChatroom:抽象聊天室类,做为Participant的交互的中介。

    Register()方法:会员注册功能;Send()方法:发送消息功能。

    Chatroom:具体聊天室类,实现抽象聊天室类中的方法。

    Participant:参与者类,主要有发送消息Send()功能和接受消息Receive()功能。

    Beatle类,NonBeatle:参与者类的具体实现,实现父类Paticipant类中的方法。

    2、代码

    1、抽象聊天室类AbstractChatroom及其具体聊天室Chatroom

    /// <summary>

    /// The 'Mediator' abstract class

    /// </summary>

    abstract class AbstractChatroom

    {

        public abstract void Register(Participant participant);

        public abstract void Send(string from, string to, string message);

    }

    /// <summary>

    /// The 'ConcreteMediator' class

    /// </summary>

    class Chatroom : AbstractChatroom

    {

        private Dictionary<string, Participant> _participants =new Dictionary<string, Participant>();

        public override void Register(Participant participant)

        {

            if (!_participants.ContainsValue(participant))

            {

                _participants[participant.Name] = participant;

            }

            participant.Chatroom = this;

     

        }

        public override void Send(string from, string to, string message)

        {

            Participant participant = _participants[to];

            if (participant != null)

            {

                participant.Receive(from, message);

            }

        }

    }

     

    2、参与者Participant类及其实现BeatleNonBeatle

    /// <summary>

    /// The 'AbstractColleague' class

    /// </summary>

    class Participant

    {

        private Chatroom _chatroom;

        private string _name;

       // Constructor

        public Participant(string name)

        {

            this._name = name;

        }

        // Gets participant name

        public string Name

        {

            get { return _name; }

        }

        // Gets chatroom

        public Chatroom Chatroom

        {

            set { _chatroom = value; }

            get { return _chatroom; }

        }

        // Sends message to given participant

        public void Send(string to, string message)

        {

            _chatroom.Send(_name, to, message);

        }

        // Receives message from given participant

       public virtual void Receive(string from, string message)

        {

            Console.WriteLine("{0} to {1}: '{2}'",from, Name, message);

        }

    }

    /// <summary>

    /// A 'ConcreteColleague' class

    /// </summary>

    class Beatle : Participant

    {

        // Constructor

        public Beatle(string name)

            : base(name)

        {

        }

        public override void Receive(string from, string message)

        {

            Console.Write("To a Beatle: ");

            base.Receive(from, message);

        }

    }

    /// <summary>

    /// A 'ConcreteColleague' class

    /// </summary>

    class NonBeatle : Participant

    {

        // Constructor

        public NonBeatle(string name)

            : base(name)

        {

        }

        public override void Receive(string from, string message)

        {

            Console.Write("To a non-Beatle: ");

            base.Receive(from, message);

        }

    }

     

    3、客户端代码

    static void Main(string[] args)

    {

        // Create chatroom

        Chatroom chatroom = new Chatroom();

        // Create participants and register them

        Participant George = new Beatle("George");

        Participant Paul = new Beatle("Paul");

        Participant Ringo = new Beatle("Ringo");

        Participant John = new Beatle("John");

        Participant Yoko = new NonBeatle("Yoko");

     

        chatroom.Register(George);

        chatroom.Register(Paul);

        chatroom.Register(Ringo);

        chatroom.Register(John);

        chatroom.Register(Yoko);

       

        // Chatting participants

        Yoko.Send("John", "Hi John!");

        Paul.Send("Ringo", "All you need is love");

        Ringo.Send("George", "My sweet Lord");

        Paul.Send("John", "Can't buy me love");

        John.Send("Yoko", "My sweet love");

        // Wait for user

        Console.ReadKey();

    }

    3、运行结果

    五、总结(Summary

    中介者模式(Mediator Pattern),定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。中介者模式一般应用于一组对象以定义良好但是复杂的方法进行通信的场合,以及想定制一个分布在多个类中的行为,而不想生成太多的子类的场合。





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值