zoukankan      html  css  js  c++  java
  • 中介者模式

     直接代码:

    1 public abstract class Mediator {
    2     public abstract void send(String message,Colleague coll);
    3 }
    Mediator
     1 public class ConcreteMediator extends Mediator {
     2     private ConcreteColleague1 colleague1;
     3     private ConcreteColleague2 colleague2;
     4     @Override
     5     public void send(String message, Colleague coll) {
     6         if(coll==colleague1){
     7             colleague2.notify(message);
     8         }else{
     9             colleague1.notify(message);
    10         }
    11     }
    12     public ConcreteColleague1 getColleague1() {
    13         return colleague1;
    14     }
    15     public void setColleague1(ConcreteColleague1 colleague1) {
    16         this.colleague1 = colleague1;
    17     }
    18     public ConcreteColleague2 getColleague2() {
    19         return colleague2;
    20     }
    21     public void setColleague2(ConcreteColleague2 colleague2) {
    22         this.colleague2 = colleague2;
    23     }
    24 }
    ConcreteMediator
    1 public abstract class Colleague {
    2     protected Mediator mediator;
    3 
    4     public Colleague(Mediator mediator) {
    5         this.mediator = mediator;
    6     }
    7 }
    Colleague
     1 public class ConcreteColleague1 extends Colleague {
     2 
     3     public ConcreteColleague1(Mediator mediator) {
     4         super(mediator);
     5     }
     6     
     7     public void sent(String message){
     8         mediator.send(message, this);
     9     }
    10     public void notify(String message){
    11         System.out.println("同事1得到消息"+message);
    12     }
    13     
    14 }
    ConcreteColleague1
     1 public class ConcreteColleague2 extends Colleague {
     2 
     3     public ConcreteColleague2(Mediator mediator) {
     4         super(mediator);
     5     }
     6     public void sent(String message){
     7         mediator.send(message, this);
     8     }
     9     public void notify(String message){
    10         System.out.println("同事2得到消息"+message);
    11     }
    12 
    13 }
    ConcreteColleague2
     1 public class MediatorTest {
     2     public static void main(String[] args) {
     3         ConcreteMediator me = new ConcreteMediator();
     4         
     5         ConcreteColleague1 c1 =new ConcreteColleague1(me);
     6         ConcreteColleague2 c2 =new ConcreteColleague2(me);
     7         
     8         me.setColleague1(c1);
     9         me.setColleague2(c2);
    10         
    11         c1.sent("吃饭了吗?");
    12         c2.sent("没有呢,你打算请客");
    13     }
    14 }
    test
    同事2得到消息吃饭了吗?
    同事1得到消息没有呢,你打算请客
    测试打印
  • 相关阅读:
    Http与WWW服务精解
    Http与WWW服务精解
    6-13
    好用的工具说明
    JVM、JRE和JDK三者间的区别和联系
    css进阶之二:flex弹性布局
    MVVM
    如何理解TCP的三次握手协议?
    java里面的设计模式
    linux常用命令
  • 原文地址:https://www.cnblogs.com/cai170221/p/13398085.html
Copyright © 2011-2022 走看看