设计模式笔记(19)--中介者模式

中介者模式

GOF对中介者模式的定义是:“用一个中介对象来封装一系列的对象交互,中介者使各个对象不需要显式地互相引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。”

以客服人员为例,上代码:

package Mediator;
//抽象客服人员
public abstract class CustomerServer {
    public abstract void Communicate(String msg, Communicator com);
}
package Mediator;

public class CustomerService extends CustomerServer{

    private Customer customer;
    private Technician technician;
    @Override
    public void Communicate(String msg, Communicator com) {
        // TODO Auto-generated method stub
        if(com == customer)
        {
            technician.GetMsg(msg);
        }
        else 
        {
            customer.GetMsg(msg);
        }
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public void setTechnician(Technician technician) {
        this.technician = technician;
    }
}
package Mediator;

public abstract class Communicator {
    protected CustomerServer customerServer;
    public Communicator(CustomerServer customerServer) {
        this.customerServer = customerServer;
    }
}
package Mediator;

public class Customer extends Communicator{

    public Customer(CustomerServer customerServer) {
        super(customerServer);
        // TODO Auto-generated constructor stub
    }
    public void Ask(String msg)
    {
        customerServer.Communicate(msg, this);
    }
    
    public void GetMsg(String msg)
    {
        System.out.println("顾客得到咨询技术人员的回复:"+msg);
    }
}
package Mediator;

public class Technician extends Communicator{

    public Technician(CustomerServer customerServer) {
        super(customerServer);
        // TODO Auto-generated constructor stub
    }
    
    public void Answer(String msg)
    {
        customerServer.Communicate(msg, this);
    }
    
    public void GetMsg(String msg)
    {
        System.out.println("顾客咨询技术人员:"+msg);
    }
}
package Mediator;

public class client {
    public static void main(String[] args)
    {
        CustomerService cs = new CustomerService();
        Customer cus = new Customer(cs);
        Technician tc = new Technician(cs);
        cs.setCustomer(cus);
        cs.setTechnician(tc);
        
        cus.Ask("我为什么这么蠢");
        tc.Answer("我不知道");
    }
}

中介者模式适用于以下几种情况

  1. 当一组对象以定义良好但是复杂的方式进行通信时,所产生的相互依赖关系结构混乱并且难以理解
  2. 当一个对象需要引用很多其他的对象并且直接与这些对象进行通信导致难以复用该对象时。

你可能感兴趣的:(设计模式笔记(19)--中介者模式)