中介者的职责太多.
一般应用在一组对象以定义良好但是复杂的方式进行通信的场合.以及想定制一个分布在多个类中的行为,而又不想生成太多子类的场合.
不要先使用中介者,要先考虑设计是否合理.
1 2 3 4 5 6 7 8 9
| package mediator;
public abstract class Mediator { public abstract void send(String message, Country country); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package mediator;
public class UnitedNations extends Mediator { private China china; private America america;
public void setChina(China china) { this.china = china; }
public void setAmerica(America america) { this.america = america; }
@Override public void send(String message, Country country) { if (country instanceof China) { america.receive(message); } else { china.receive(message); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| package mediator;
public class Country { protected Mediator unitedNations;
public Country(Mediator unitedNations) { this.unitedNations = unitedNations; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package mediator;
public class China extends Country { public China(Mediator unitedNations) { super(unitedNations); }
public void declare(String message) { unitedNations.send(message, this); }
public void receive(String message) { System.out.println("中国收到: " + message); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package mediator;
public class America extends Country { public America(Mediator unitedNations) { super(unitedNations); }
public void declare(String message) { unitedNations.send(message, this); }
public void receive(String message) { System.out.println("美国收到: " + message); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package mediator;
public class Main { public static void main(String[] args) { UnitedNations un = new UnitedNations(); China china = new China(un); America america = new America(un);
un.setAmerica(america); un.setChina(china);
america.declare("第三次世界大战"); china.declare("无条件投降"); } }
|