文章目录
一、中介者模式
用一个中介对象来封装一系列的对象交互。中介者使各个对象业务之间不显示的相互调用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
二、中介者模式示例代码
以房产中介为例,如果没有房产中介,购房需要客户到各个楼盘进行咨询房子的信息,房产中介可以为顾客提供所有楼盘的信息。
1.定义抽象中介类
/**
* 房产中介
*/
public abstract class HouseMediator {
public abstract void sendHouseInfo(String houseInfo);
}
2.具体的抽象中介实现类
代码如下:
public class HouseMediatorA extends HouseMediator{
@Override
public void sendHouseInfo(String houseInfo) {
System.out.println("HouseMediatorA:"+houseInfo);
}
}
3.定义具体类
package behavior.Mediator;
/**
* 楼盘信息
*/
public class CommercialBuilding {
private String houseDesc;
private String housePrice;
private String houseAddr;
private HouseMediator houseMediator;
public CommercialBuilding(String houseDesc, String housePrice, String houseAddr,HouseMediator houseMediator) {
this.houseDesc = houseDesc;
this.housePrice = housePrice;
this.houseAddr = houseAddr;
this.houseMediator = houseMediator;
}
public String getHouseDesc() {
return houseDesc;
}
public void setHouseDesc(String houseDesc) {
this.houseDesc = houseDesc;
}
public String getHousePrice() {
return housePrice;
}
public void setHousePrice(String housePrice) {
this.housePrice = housePrice;
}
public String getHouseAddr() {
return houseAddr;
}
public void setHouseAddr(String houseAddr) {
this.houseAddr = houseAddr;
}
/**
* 发布房产信息
*
*/
public void sendHouseInfo(){
String houseInfo = "CommercialBuilding[" +
"houseDesc='" + houseDesc + '\'' +
", housePrice='" + housePrice + '\'' +
", houseAddr='" + houseAddr + '\'' +
']';
houseMediator.sendHouseInfo(houseInfo);
}
}
4.测试
public class MediatorDemo {
public static void main(String[] args) {
CommercialBuilding commercialBuilding = new CommercialBuilding("A","9000/m^2","北京路",new HouseMediatorA());
commercialBuilding.sendHouseInfo();
commercialBuilding = new CommercialBuilding("B","10000/m^2","上海路",new HouseMediatorA());
commercialBuilding.sendHouseInfo();
}
}
打印:
HouseMediatorA:CommercialBuilding[houseDesc='A', housePrice='9000/m^2', houseAddr='北京路']
HouseMediatorA:CommercialBuilding[houseDesc='B', housePrice='10000/m^2', houseAddr='上海路']
总结
抽象中介者(Mediator)角色:抽象中介者角色定义统一的接口用于各同事角色之间的通信。具体中介者(Concrete Mediator)角色:具体中介者角色通过协调各同事角色实现协作行为,因此它必须依赖于各个同事角色。同事(Colleague)角色:每一个同事角色都知道中介者角色,而且与其他的同事角色通信的时候,一定要通过中介者角色协作。每个同事类的行为分为两种:一种是同事本身的行为,比如改变对象本身的状态,处理自己的行为等等,这种方法叫做自发行为(Self-Method),与其他的同事类或中介者没有任何的依赖;第二种是是必须依赖中介者才能完成的行为,叫做依赖方法(Dep-Method)。