关闭

设计模式之Mediator模式(笔记)

标签: mediator
438人阅读 评论(0) 收藏 举报
分类:

中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立的改变它们之间的交互。
使用场合:中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而不是想生成太多的子类的场合。

这里写图片描述

首先定义一个中介者接口IMediator

public interface IMediator {

    public void send(String message,Colleague colleague);
}

接着定义抽象同事类Colleague

public abstract class Colleague {

    protected IMediator mediator;

    public Colleague(IMediator mediator){
        this.mediator=mediator;
    }
}

接着定义具体的同事类继承Colleague 抽象同事类

public class ConcreteColleague1 extends Colleague{

    public ConcreteColleague1(IMediator mediator) {
        super(mediator);

    }

    public void send(String message){
        mediator.send(message, this);
    }

    public void notify(String message){
        System.out.println("同事1获得消息:"+message);
    }
}


public class ConcreteColleague2 extends Colleague{

    public ConcreteColleague2(IMediator mediator) {
        super(mediator);

    }

    public void send(String message){
        mediator.send(message, this);
    }

    public void notify(String message){
        System.out.println("同事2获得消息:"+message);
    }
}

然后定义一个具体的中介者对象ConcreteMediator继承IMediator

public class ConcreteMediator implements IMediator{

    private ConcreteColleague1 colleague1;
    private ConcreteColleague2 colleague2;

    public void setColleague1(ConcreteColleague1 colleague1){
        this.colleague1=colleague1;
    }

    public ConcreteColleague1 getColleague1(){
        return colleague1;
    }

    public void setColleague2(ConcreteColleague2 colleague2){
        this.colleague2=colleague2;
    }

    public ConcreteColleague2 getColleague2(){
        return colleague2;
    }

    @Override
    public void send(String message, Colleague colleague) {

        if(colleague==colleague1){
            colleague2.notify(message);
        }
        else{
            colleague1.notify(message);
        }       
    }
}

客户端代码

public static void main(String[] args) {
 //中间者模式
ConcreteMediator mediator=new ConcreteMediator();
ConcreteColleague1 colleague1=new ConcreteColleague1(mediator);
ConcreteColleague2 colleague2=new ConcreteColleague2(mediator);

mediator.setColleague1(colleague1);
mediator.setColleague2(colleague2);

colleague1.send("你好,中国");
colleague2.send("你好,美国");
}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30812次
    • 积分:858
    • 等级:
    • 排名:千里之外
    • 原创:54篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条