GoF Definition:
Define an object that encapsulates how a set of objects interacts. The mediator pattern promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
概念
中介者负责一系列对象的交流,用来系统之间的解耦。
例子
通常情况下,航班与航班之间通过航空塔交流。
代码实现
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
public abstract class { public abstract void send (Friend friend, String msg) ; } public class ConcreteMediator extends { private FriendOne one; private FriendTwo two; private Boss boss; public void setFriendOne (FriendOne one) { this .one = one; } public void setFriendTwo (FriendTwo two) { this .two = two; } public void setBoss (Boss boss) { this .boss = boss; } public void send (Friend friend, String msg) { if (friend == one) { two.notify(msg); boss.notify(one.name + " sends message to " + two.name); } if (friend == two) { one.notify(msg); boss.notify(two.name + " sends message to " + one.name); } if (friend == boss) { one.notify(msg); two.notify(msg); } } } public abstract class Friend { protected Mediator mediator; public String name; public Friend (Mediator mediator) { this .mediator = mediator; } } public class Boss extends Friend { public Boss (Mediator mediator, String name) { super (mediator); this .name = name; } public void send (String msg) { mediator.send(this , msg); } public void notify (String msg) { System.out.println("Boss sees message: " + msg); } } public class FriendOne extends Friend { public FriendOne (Mediator mediator, String name) { super (mediator); this .name = name; } public void send (String msg) { mediator.send(this , msg); } public void notify (String msg) { System.out.println("Amit gets message: " + msg); } } public class FriendTwo extends Friend { public FriendTwo (Mediator mediator, String name) { super (mediator); this .name = name; } public void send (String msg) { mediator.send(this , msg); } public void notify (String msg) { System.out.println("Sohrl get message: " + msg); } }
近期评论