设计模式--中介者模式

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

//抽象基类

//国家
abstract class Country
{
protected UnitedNations mediator;
public Country(UnitedNations mediator)
{
this.mediator = mediator;
}
}

//具体实现

//美国

class USA : Country
{
public USA(UnitedNations mediator) : base(mediator)
{
}

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

public void GetMessage(string message)
{
Console.WriteLine("美国获得对方信息:" + message);
}

}

//伊拉克
class Iraq : Country
{
public Iraq(UnitedNations mediator) : base(mediator)
{
}
public void Declare(string message)
{
mediator.Deciare(message, this);
}
public void GetMessage(string message)
{
Console.WriteLine("伊拉克获得对方信息:" + message);
}
}

//中介者

//中介者基类

//联合国机构
abstract class UnitedNations
{
public abstract void Deciare(string message, Country country);
}

//具体实现

//联合国安全理事会
class UnitedNationsSecurityCouncil:UnitedNations
{
USA col1;
Iraq col2;
public USA Col1 { set { col1 = value; } }
public Iraq Col2 { set { col2 = value; } }

public override void Deciare(string message, Country country)
{
if(country == col1)
{
col2.GetMessage(message);
}
else
{
col1.GetMessage(message);
}
}
}

调用:

UnitedNationsSecurityCouncil unsc = new UnitedNationsSecurityCouncil();
USA c1 = new USA(unsc);
Iraq c2 = new Iraq(unsc);
unsc.Col1 = c1;
unsc.Col2 = c2;

c1.Declare("不准研制核武器,否则要发动战争!");
c2.Declare("我们没有核武器,也不怕侵略!");

原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/6732556.html