中介者模式 对象和对象直接不直接交互,而是通过一个中介者来实现对象之间的交互。使原有对象之间的关系变得松散,且可以通过定义不同的中介者来改变他们之间的交互。
(1)定义房东
public class Landlord{ private final static Log logger = LogFactory.getLog(this.getClass()); public boolean operation(String msg){ logger.info("landlord receive a message from mediator"+msg); return true; } }
(2)定义租户
public class Tenant{ private final static Log logger = LogFactory.getLog(this.getClass()); public boolean operation(String msg){ logger.info("tenant receive a message from mediator"+msg); return true; } }
(3)定义中介
public abstract class Mediator{ protected Landlord landlord; protected Tenant tenant; public Mediator(Landlord landlord,Tenant tenant){ this.landlord = landlord; this.tenant = tenant; } public abstract boolean notifyTenant(String msg); public abstract boolean notifyLandlord(String msg); } public class ConcreteMediator extends Mediator{ public ConcreteMediator(Landlord landlord,Tenant tenant){ super(landlord,tenant); } @Override public boolean notifyTenant(String msg) { if (tenant != null){ return tenant.operation(msg); } return false; } @Override public boolean notifyLandlord(String msg) { if (landlord != null){ return landlord.operation(msg); } return false; } }
(4)使用中介者模式
public static void main(String[] args){ Landlord landlord = new Landlord(); Tenant tenant = new Tenant(); ConcreteMediator concreteMediator = new ConcreteMediator(landlord,tenant); boolean result = concreteMediator.notifyTenant("想租两室一厅吗?"); if (result){ concreteMediator.notifyLandlord("租客对面积满意"); }else { concreteMediator.notifyLandlord("租客对面积不满意"); } }