初尝Mediator 模式
在日常生活中,我们经常会遇到多个事物相互之间都有联系的例子。例如:聊天室。
在软件构建过程中,经常会出现多个对象互相关联交互的情况,对象之间常常会维持一种复杂的引用关系,如果遇到一些需求的更改,这种直接的引用关系将面临不断的变化。在这种情况下,我们可使用一个“中介对象”来管理对象间的关联关系,避免相互交互的对象之间的紧耦合引用关系,从而更好地抵御变化。
意图
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
结构图
在这里,我们模拟一个聊天室的程序,用户既可以对特定的对象进行发送消息,也可以向所有人say hello。我们用一个mediator 对象进行管理他们之间的联系。值得指出的是,代码中,仍有值得抽象的接口。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mediator
{
class Program
{
static void Main(string[] args)
{
ChatRoom cr = new ChatRoom();
Participator p = new Participator("Shao mingbo",cr);
Participator p2 = new Participator("YW",cr);
Participator p3 = new Participator("ZZ",cr);
Participator p4 = new Participator("Xiao Di",cr);
//Say Hello to The One
p.Send(p2,"Hello");
Console.WriteLine("--------------");
// Say Hi To All
p4.Send("Hi");
}
}
class Participator {
private string _name;
private ChatRoom cr;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Participator(string name,ChatRoom cr) {
this._name = name;
this.cr = cr;
cr.RegistParticipator(this);
}
public void Receive(string from,string msg) {
if(cr!=null)
Console.WriteLine("{0} 收到来自 {1}的一则消息: {2}", this.Name, from, msg);
else
Console.WriteLine("{0} 未曾在聊天室内注册!", this._name);
}
public void Send(Participator p,string msg) {
if (cr != null) {
cr.RegistParticipator(this);
cr.Notify(this.Name,p, msg);
}
else
Console.WriteLine("{0} 未曾在聊天室内注册!",this._name);
}
public void Send(string msg) {
this.Send(null,msg);
}
}
class ChatRoom {
private Dictionary roomMate = new Dictionary();
public void RegistParticipator(Participator p) {
if (!roomMate.ContainsKey(p.Name))
roomMate.Add(p.Name,p);
}
public void Notify(string from,Participator p, string msg) {
if (p != null)
{
p.Receive(from, msg);
}
else {
foreach (var receiver in roomMate) {
if (receiver.Key != from) {
Participator r = receiver.Value;
r.Receive(from,msg);
}
}
}
}
}
}
运行结果:


近期评论