您的位置:首页 > 其它

二十.行为型设计模式——Mediator Pattern(中介者模式)

2011-09-23 23:50 661 查看

定义

  定义一个对象封装一系列多个对象如何互相作用。Mediator中介者使得对象之间不需要显示地互相引用,从而使得其耦合更加松散。并且还让我们可以独立变化多个对象的互相作用。

  UML类图如下:  

  View Code

//中介者接口
interface IChatroom
{
void Register(Participant participant);
void Send(string from, string to, string message);
}

//具体中介者-聊天室类
class Chatroom : IChatroom
{
//参与者
private Hashtable participants = new Hashtable();
//先注册参与者
public void Register(Participant participant)
{
if (participants[participant.Name] == null)
participants[participant.Name] = participant;
participant.Chatroom = this;
}
//发送信息
public void Send(string from, string to, string message)
{
Participant pto = (Participant)participants[to];
if (pto != null)
pto.Receive(from, message);
}
}

//参与者基类
class Participant
{
private Chatroom chatroom;
private string name;

public Participant(string name)
{
this.name = name;
}
//具有聊天室属性
public Chatroom Chatroom
{
get { return chatroom; }
set { chatroom = value; }
}
public string Name
{
get { return name; }
}
//发送消息,调用聊天室类的发送方法
public void Send(string to, string message)
{
chatroom.Send(name, to, message);
}
//虚拟接收函数
public virtual void Receive(string from, string message)
{
Console.WriteLine("{0} yo {1} : '{2}'", from, this.name, message);
}
}

//具体同事类-Beatle参与者
class BeatleParticipant : Participant
{
public BeatleParticipant(string name) : base(name) { }
public override void Receive(string from, string message)
{
Console.Write("To a Beatle");
base.Receive(from, message);
}
}

//具体同事类-非Beatle参与者
class NonBeatleParticipant : Participant
{
public NonBeatleParticipant(string name) : base(name) { }
public override void Receive(string from, string message)
{
Console.Write("To a non-Beatle");
base.Receive(from, message);
}
}

//中介者模式测试程序
class Program
{
static void Main(string[] args)
{
//创建聊天室
Chatroom c = new Chatroom();
//创造参与者及登入聊天室
Participant George = new BeatleParticipant("George");
Participant Paul = new BeatleParticipant("Paul");
Participant Ringo = new BeatleParticipant("Ringo");
Participant John = new BeatleParticipant("John");
Participant Yoko = new NonBeatleParticipant("Yoko");
c.Register(George);
c.Register(Paul);
c.Register(Ringo);
c.Register(John);
c.Register(Yoko);
//成员间聊天
Yoko.Send("John", "Hi John!");
Paul.Send("Ringo", "All you need is love");
Ringo.Send("John", "My sweet Lord");
Paul.Send("John", "Can't buy me love");
John.Send("Yoko", "My sweet love");
Console.Read();
}
}


优势和缺陷:

  中介者模式分离了两个同事类,简化了对象协议,中央控制对象交互,从而使个体对象变得更容易且更简单,因为它不需要传递数据给其他个体对象,仅仅传给中介者就可以了。个体对象不需要具有处理内部交流的逻辑,所以更加突出它的面向对象特性。

应用情景:

  下面的情景很适合应用中介者模式:

  1.一组对象复杂地互相通信但其方法是定义明确的。

  2.若干个对象需要定义方法又不需要子类实现。

  中介者模式通常用在基于信息通信的系统结构中。这种信息传递到关联的对象,其自身不直接链接。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: