美文网首页
设计模式-中介模式

设计模式-中介模式

作者: Wu杰语 | 来源:发表于2020-12-31 08:07 被阅读0次

    中介模式是在各方交互比较复杂的时候,抽象出一个中介来减少各方交互。我们举一个聊天室的例子:

    例子

    public class ChatRoom {
       public static void showMessage(User user, String message){
          System.out.println(new Date().toString()
             + " [" + user.getName() +"] : " + message);
       }
    }
    
    public class User {
       private String name;
     
       public String getName() {
          return name;
       }
     
       public void setName(String name) {
          this.name = name;
       }
     
       public User(String name){
          this.name  = name;
       }
     
       public void sendMessage(String message){
          ChatRoom.showMessage(this,message);
       }
    }
    
    public class Application{
       public static void main(String[] args) {
          User xiaoming = new User("XiaoMing");
          User xiaohong = new User("XiaoHong");
     
          xiaoming .sendMessage("Hi! XiaoHong!");
          xiaohong.sendMessage("Hello! Xiaoming!");
       }
    }
    
    
    

    所有的User都跟聊天室交互,聊天室就是中介。

    小结

    中介模式在现实中也运用很多,例如说飞机塔台、火车控制室等。

    相关文章

      网友评论

          本文标题:设计模式-中介模式

          本文链接:https://www.haomeiwen.com/subject/cwycoktx.html