中介者模式也是用來下降類類之間的耦合的,由於若是類類之間有依賴關係的話,不利於功能的拓展和維護,由於只要修改一個對象,其它關聯的對象都得進行修改。若是使用中介者模式,只需關心和Mediator類的關係,具體類類之間的關係及調度交給Mediator就行,這有點像spring容器的做用。先看看圖:java
User類統一接口,User1和User2分別是不一樣的對象,兩者之間有關聯,若是不採用中介者模式,則須要兩者相互持有引用,這樣兩者的耦合度很高,爲了解耦,引入了Mediator類,提供統一接口,MyMediator爲其實現類,裏面持有User1和User2的實例,用來實現對User1和User2的控制。這樣User1和User2兩個對象相互獨立,他們只須要保持好和Mediator之間的關係就行,剩下的全由MyMediator類來維護!基本實現:spring
public interface Mediator { public void createMediator(); public void workAll(); }
public class MyMediator implements Mediator { private User user1; private User user2; public User getUser1() { return user1; } public User getUser2() { return user2; } @Override public void createMediator() { user1 = new User1(this); user2 = new User2(this); } @Override public void workAll() { user1.work(); user2.work(); } }
public abstract class User { private Mediator mediator; public Mediator getMediator(){ return mediator; } public User(Mediator mediator) { this.mediator = mediator; } public abstract void work(); }
public class User1 extends User { public User1(Mediator mediator){ super(mediator); } @Override public void work() { System.out.println("user1 exe!"); } }
public class User2 extends User { public User2(Mediator mediator){ super(mediator); } @Override public void work() { System.out.println("user2 exe!"); } }
測試類:ide
public class Test { public static void main(String[] args) { Mediator mediator = new MyMediator(); mediator.createMediator(); mediator.workAll(); } }
輸出:測試
user1 exe!
user2 exe!this