码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之中介者模式

时间:2017-10-07 14:27:49      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:str   dia   media   nta   new   rgs   oid   nts   rri   

中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而解耦,而且可以独立地改变他们之间的交互。

 

public abstract class Component {
    protected Mediator mediator;

    public Component(Mediator mediator) {
        this.mediator = mediator;
    }
}

public class ConcreteComponent_A extends Component {
    public ConcreteComponent_A(Mediator mediator) {
        super(mediator);
    }

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

    public void notifys(String message) {
        System.out.println("成员A得到消息:" + message);
    }
}

public class ConcreteComponent_B extends Component {
    public ConcreteComponent_B(Mediator mediator) {
        super(mediator);
    }

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

    public void notifys(String message) {
        System.out.println("成员B得到消息:" + message);
    }
}

 

public interface Mediator {
    public void sendMessage(String message,Component component);
}

 

public class ConcreteMediator implements Mediator {
    private ConcreteComponent_A concreteComponentA;
    private ConcreteComponent_B concreteComponentB;

    public void setConcreteComponentA(ConcreteComponent_A concreteComponentA) {
        this.concreteComponentA = concreteComponentA;
    }

    public void setConcreteComponentB(ConcreteComponent_B concreteComponentB) {
        this.concreteComponentB = concreteComponentB;
    }

    @Override
    public void sendMessage(String message, Component component) {
        if (component == concreteComponentA) {
            concreteComponentB.notifys(message);
        } else {
            concreteComponentA.notifys(message);
        }
    }
}

 

public class MediatorDemo {
    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator();
        ConcreteComponent_A concreteComponentA = new ConcreteComponent_A(mediator);
        ConcreteComponent_B concreteComponentB = new ConcreteComponent_B(mediator);

        mediator.setConcreteComponentA(concreteComponentA);
        mediator.setConcreteComponentB(concreteComponentB);

        concreteComponentA.send("购物车清空了吗?");
        concreteComponentB.send("没有,你打算买单?");

    }
}

 

设计模式之中介者模式

标签:str   dia   media   nta   new   rgs   oid   nts   rri   

原文地址:http://www.cnblogs.com/emoji1213/p/7634245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!