java23種設計模式-中介者模式
阿新 • • 發佈:2018-12-11
定義
用一箇中介物件來封裝一系列的物件互動,中介者使各物件不需要顯式地相互引用,從而使其耦合鬆散,而且可以獨立地改變它們之間的互動。
角色
- Colleague:是一個抽象類或者介面,提供和其他Colleague通訊的方法 notify(String name)。引數name是其他Colleague的名字。
- ColleagueA,ColleagueB: 都是Colleague的實現類。
- Mediator: 中介者類,聚合了一系列的同事類,使得它們之間可以相互通訊。具體同事類ColleagueA等都是通過Mediator,呼叫Mediator的notify(String name)方法向其他同事類傳送訊息。notify(String name)通過name找到集合中對應的Colleague並向其傳遞訊息。Mediator類提供add(Colleague colleague)方法增加自己維護的Colleague集合中的物件。
UML
實現
/**
* desc : 同事介面
* Created by tiantian on 2018/9/23
*/
public interface Colleague {
void notify(String name);
void receive();
String getName();
}
/** * desc : 具體同事A * Created by tiantian on 2018/9/23 */ public class ColleagueA implements Colleague{ private String name; public ColleagueA(String name) { this.name = name; } @Override public void notify(String name) { Mediator.notify(name); } @Override public void receive() { System.out.println("ColleagueA received message"); } @Override public String getName() { return name; } }
/** * desc : 具體同事A * Created by tiantian on 2018/9/23 */ public class ColleagueB implements Colleague{ private String name; public ColleagueB(String name) { this.name = name; } @Override public void notify(String name) { Mediator.notify(name); } @Override public void receive() { System.out.println("ColleagueB received message"); } @Override public String getName() { return name; } }
/**
* desc : 媒介類
* Created by tiantian on 2018/9/23
*/
public class Mediator {
private static Map<String, Colleague> colleagues = new HashMap<>();
public static void notify(String name) {
Colleague colleague = colleagues.get(name);
colleague.receive();
}
public static void add(Colleague colleague) {
colleagues.put(colleague.getName(), colleague);
}
}
public class Test {
public static void main(String[] args) {
Colleague colleagueA = new ColleagueA("colleagueA");
Colleague colleagueB = new ColleagueB("colleagueB");
Mediator.add(colleagueA);
Mediator.add(colleagueB);
colleagueA.notify("colleagueB");
}
}
總結
中介者模式使得物件之間網狀的依賴關係變成星型依賴關係。物件之間通訊時不必顯式的相互呼叫,而是通過中介者間接的傳遞訊息。這種依賴關係也符合迪米特原則。該模式缺點是,當需要互相通訊的同事類數量很多的時候,中介者的複雜度將變的很高,維護難度也隨之增加。