首页 > 代码库 > 中介者模式

中介者模式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*


中介者模式

*
* 集中控制
* 所有的操作都通过中介进行转发处理


*/

namespace App_MYCS.HDL_SJMS.ZJMS.ZJMS
{
class my_ZJMS
{
public void DY()
{
ConcreteMediator cm = new ConcreteMediator();//中介者类

Colleague1 c1 = new Colleague1(cm);
Colleague2 c2 = new Colleague2(cm);

//中介认识所有同事类
cm.Colleaguel = c1;
cm.Colleague2 = c2;

//
c1.Send("aaaa");
c2.Send("bbbb");

}

}

//抽像中介者类
abstract class Mediator
{
public abstract void Send(string message,Colleague colleague);
}

//中介者类
class ConcreteMediator : Mediator
{
private Colleague1 colleaguel;

internal Colleague1 Colleaguel
{
set { colleaguel = value; }
}
private Colleague2 colleague2;

internal Colleague2 Colleague2
{
set { colleague2 = value; }
}

public override void Send(string message, Colleague colleague)
{
if (colleague == colleaguel)
{
colleague2.Notify(message);
}
else
{
colleaguel.Notify(message);
}
}


}

//抽像同事类
abstract class Colleague
{
protected Mediator mediator;

public Colleague(Mediator m)
{
this.mediator = m;
}
}

//各种同事类
class Colleague1 : Colleague
{
public Colleague1(Mediator m)
:base(m)
{

}
//通过中介类进行发送
public void Send(string message)
{
mediator.Send(message,this);
}

public void Notify(string message)
{
Console.WriteLine("同事1 得到消息"+message);
}
}

class Colleague2 : Colleague
{
public Colleague2(Mediator m)
: base(m)
{

}

public void Send(string message)
{
mediator.Send(message, this);
}

public void Notify(string message)
{
Console.WriteLine("同事2 得到消息" + message);
}
}

}

中介者模式