设计模式---中介者模式

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

 

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

    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值