设计模式 - 中介者模式

2016-09-04  本文已影响68人  Mitchell
//中介基类
abstract class Mediator
{
    public abstract void Send(string message,Colleague colleague);
}
//同事类
abstract class Colleague
{
    protected Mediator mediator;
    public Colleague(Mediator mediator){
        this.mediator = mediator;
    }
}
class ConcreteMediator : Mediator
{
    private ConcreteColleague1 cooleague1;
    private ConcreteColleague2 cooleague2;

    public ConcreteColleague1 Colleague1
    {
        set{ Colleague1 = value; }
    }
    public ConcreteColleague2 Colleague2
    {
        set{ Colleague2 = value; }
    }
    public override void Send(stirng message,Colleague colleague){
        if(colleague == Colleague1)
        {
            Colleague1.Notify(message);
        }else{
            Colleague2.Notify(message);
        }
    }
}
class ConcreteColleague1 :Colleague
{
    public ConcreteColleague1 (Mediator mediator):base(mediator)
    [

    ]
    public void Send(string message)
    {
        mediator.Send(message,this);
    }
    public void Notify(string message)
    {
        Console.WriteLine("同事1得到的消息是:"+message);
    }
}
class ConcreteColleague2 :Colleague
{
    public ConcreteColleague2 (Mediator mediator):base(mediator)
    [

    ]
    public void Send(string message)
    {
        mediator.Send(message,this);
    }
    public void Notify(string message)
    {
        Console.WriteLine("同事2得到的消息是:"+message);
    }
}
static void Main(string[] args){
    //创建中介类
    ConcreteMediator M = new ConcreteMediator();
    //
    ConcreteColleague1 c1 = new ConcreteColleague1(m);
    ConcreteColleague2 c1 = new ConcreteColleague2(m);
    m.Colleague1 = c1;
    m.Colleague2 = c2;
    c1.Send("message1");
    c2.Send("message2");
    Console.Read();
}
上一篇 下一篇

猜你喜欢

热点阅读