1.中介者模式简介
中介者模式(Mediator Pattern)是用来降低多个对象和类之间通信的复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使网状结构变为星型结构,使代码易于维护。中介者模式属于行为型模式。
2.试验Demo
import java.util.Date; /*ChatRoom扮演一个中介者的身份,所有人通过它发信息给所有人*/ class ChatRoom { public static void showMessage(User user, String message) { System.out.println("[ " + new Date().toString() + " ] " + user.getName() + ": " + message); } } class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void sendMessage(String message) { ChatRoom.showMessage(this, message); } } public class MediatorPatternDemo { public static void main(String args[]) { User u1 = new User("Jone"); User u2 = new User("Marel"); u1.sendMessage("Hello, I am Jone"); u2.sendMessage("Hello, I am Marel"); } } /* $ java MediatorPatternDemo [ Thu Apr 18 01:58:42 PDT 2019 ] Jone: Hello, I am Jone [ Thu Apr 18 01:58:42 PDT 2019 ] Marel: Hello, I am Marel */
参考:http://www.runoob.com/design-pattern/mediator-pattern.html