无废话设计模式(17)行为型模式--中介者模式
0-前言
中介者模式定义(Mediator):
用一个中介对象来封装一系列的对象交互。
中介者对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
1-实现
1-1、简单UML图
1-2、代码实现
//1、中介者抽象父类(客服父类)----------------------------------------- abstract class CustomerServer { abstract void Communicate(String message,Communicator communicator); } //1-1、具体中介者(客服MM) class CustomerServerMM extends CustomerServer { //A、设置客服服务的对象 private Customer customer; private Technician technician; public void setCustomer(Customer _customer) { this.customer = _customer; } public void setTechnician(Technician _technician) { this.technician = _technician; } //B、客服开始沟通 @Override public void Communicate(String message, Communicator communicator) { if (communicator ==customer) //顾客 { technician.GetMessage(message); } else { customer.GetMessage(message); } } } //2、服务对象抽象父类------------------------------------------------- abstract class Communicator { protected CustomerServer customerServer; //中介者 public Communicator(CustomerServer _customerServer) { this.customerServer = _customerServer; } } //2-1、服务对象具体类(顾客) class Customer extends Communicator { public Customer(CustomerServer customerServer) { super(customerServer); } //A、咨询 public void Ask(String message) { customerServer.Communicate(message,this); } //B、获得回复 public void GetMessage(String message) { System.out.println("顾客得到技术人员的回复:"+message); } } //2-2、服务对象具体类(维修技术人员) class Technician extends Communicator { public Technician(CustomerServer customerServer) { super(customerServer); } //A、回复 public void Anser(String message) { customerServer.Communicate(message,this); } //B、获得问题 public void GetMessage(String message) { System.out.println("技术人员接收到顾客的问题:"+message); }
客户端
CustomerServerMM csMM = new CustomerServerMM(); Customer customer = new Customer(csMM); Technician technician = new Technician(csMM); csMM.setCustomer(customer); csMM.setTechnician(technician); customer.Ask("为什么我的电脑开不了机"); technician.Anser("电池没插电源没插,开啥机!");
运行结果
2-应用场景简单总结
1、当一组对象以定义良好但是复杂的方式进行相互通讯时;
2、当一个对象需要引用很多其他对象并与这些对象通讯时;