设计模式之中介者模式
Posted emoji-emoji
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之中介者模式相关的知识,希望对你有一定的参考价值。
中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而解耦,而且可以独立地改变他们之间的交互。
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("没有,你打算买单?"); } }
以上是关于设计模式之中介者模式的主要内容,如果未能解决你的问题,请参考以下文章