(二十)中介者模式
中介者模式(Mediator Pattern)指通过一个中介对象实现系统间的访问,使得系统中各对象不需要显式地相互作用,做到解耦。
1,中介者模式的设计原则
1,抽象中介者(Mediator):定义一个抽象的统一接口;
2,具体中介者(ConcreteMediator):处理具体的对象信息;
3,抽象同事(Colleague):每一个同事都需要依赖中介者角色,与其他同事通信;
4,具体同事(ConcreateColleague):负责实现自发行为。
2,简单例子
聊天室将各聊天对象隔离,就是一个中介者的体现。
public class User {
private String name;
private ChatRoom chatRoom;
public User(String name, ChatRoom chatRoom) {
this.name = name;
this.chatRoom = chatRoom;
}
public String getName() {
return name;
}
// 用户直接和聊天室绑定了
public void sendMessage(String msg) {
this.chatRoom.showMsg(this, msg);
}
}
public class ChatRoom {
// 聊天室方法展示聊天用户和消息
public void showMsg(User user,String msg){
System.out.println("["+user.getName()+"]:"+msg);
}
}
public class Client {
public static void main(String[] args) {
ChatRoom room = new ChatRoom();
User alice = new User("alice",room);
User bob = new User("bob",room);
alice.sendMessage("hi,i am alice,bob!");
bob.sendMessage("hi,this is bob!");
}
}
3,中介者模式的点评
中介者模式能够实现类间的解耦,各类各司其职。但是,当类多时,中介者就会变得臃肿,系统复杂度升高。