设计模式之中介者模式

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

 

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("没有,你打算买单?");

    }
}

 

posted @ 2017-10-07 10:23  emoji的博客  阅读(124)  评论(0编辑  收藏  举报