中介者模式,日常很容易會使用到,本質是封裝了不一樣對象的交互細節,而不是直接交互,承擔的職責不少,可是通訊效率其實反而變差了。markdown
用一箇中介對象封裝一系列的對象交互,中介者使各對象不須要顯示地相互做用,從而使其耦合鬆散,並且能夠獨立地改變它們之間的交互。ide
//通用抽象中介者
public abstract class Mediator{
//定義組件類
protected ConcreteComponent1 c1;
protected ConcreteComponent2 c2;
public ConcreteComponent1 getC1(){
return c1;
}
public ConcreteComponent2 getC2(){
return c2;
}
public void setC1(ConcreteComponent1 c1){
this.c1 = c1;
}
public void setC2(ConcreteComponent2 c2){
this.c2 = c2;
}
//中介者模式地業務邏輯
public abstract void doSomething1();
public abstract void doSomething2();
}
//通用中介者
public class ConcreteMediator extends Mediator{
@Override
public void doSomething1(){
//調用組件類的方法
super.c1.selfMethod1();
super.c2.selfMethod2();
}
public void doSomething2(){
super.c1.selfMethod1();
super.c2.selfMethod2();
}
}
//抽象組件類
public abstract class Component{
protected Mediator mediator;
piublic Component(Mediator _mediator){
this.mediator = _mediator;
}
}
//具體組件類
public class ConcreteComponent1 extends Component{
public ConcreteComponent1(Mediator _mediator){
super(_mediator);
}
public void selfMethod1(){
//本身的業務邏輯
}
public void depMethod1(){
//本身的業務邏輯
super.mediator.doSomething1();
}
}
複製代碼
從模板代碼中應該能夠看出,中介者對象就是用於處理對象與對象之間的直接交互,封裝了多個對象之間的交互細節。this
舉個例子,聊天室發送消息的功能spa
//抽象的聊天室類
public interface ChatRoom {
void sendMessage(String msg, String userId);
void addUser(User user);
}
//具體的聊天室類
public class ChatRoomImpl implements ChatRoom {
private Map<String, User> usersMap = new HashMap<>();
@Override
public void sendMessage(String msg, String userId) {
User u = usersMap.get(userId);
u.receive(msg);
}
@Override
public void addUser(User user) {
this.usersMap.put(user.getId(), user);
}
}
//抽象的組件類
public abstract class User {
private ChatRoom mediator;
private String id;
private String name;
public User(ChatRoom room, String id, String name){
this.mediator = room;
this.name = name;
this.id = id;
}
public abstract void send(String msg, String userId);
public abstract void receive(String msg);
public ChatRoom getMediator() {
return mediator;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
//具體的組件類
public class ChatUser extends User {
public ChatUser(ChatRoom room, String id, String name) {
super(room, id, name);
}
@Override
public void send(String msg, String userId) {
System.out.println(this.getName() + " :: Sending Message : " + msg);
getMediator().sendMessage(msg, userId);
}
@Override
public void receive(String msg) {
System.out.println(this.getName() + " :: Received Message : " + msg);
}
}
複製代碼
當在類圖中出現了蜘蛛網狀結構,能夠考慮使用中介者模式,梳理爲星型結構設計
系統中對象之間存在複雜的引用關係時code
經過一箇中間對象來封裝多個類中的共有行爲時orm
減小對象之間的直接交互,間接解耦過多依賴對象
減小子類的建立數量,簡化系統的設計和實現get
經過中間層,能夠實現快速擴展,提高代碼擴展性it
中間層,即中介者類的交互邏輯可能比較複雜,後續難以維護
中介者演變承了新的重度依賴對象
中介者須要知道全部對象交互的邏輯