又叫调停模式,定义一个中介角色来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立的改变它们之间的交互。
租房:房主将房屋托管给中介,而租房者从房屋中介获取房屋信息。房屋中介充当租房者与房屋所有者之间的中介者。
类图如下:
/**
* 抽象中介者类
*/
public abstract class Mediator {
public abstract void constact(String message,Person person);
}
/**
* 具体的中介者
*/
public class MediatorStructure extends Mediator{
// 聚合房主和租房者对象
private HouseOwner houseOwner;
private Tenant tenant;
public HouseOwner getHouseOwner() {
return houseOwner;
}
public void setHouseOwner(HouseOwner houseOwner) {
this.houseOwner = houseOwner;
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
@Override
public void constact(String message, Person person) {
if (person == houseOwner){
tenant.getMessage(message);
} else {
houseOwner.getMessage(message);
}
}
}
/**
* 抽象同事类
*/
public abstract class Person {
protected String name;
protected Mediator mediator;
public Person(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
}
/**
* 具体同事类
*/
public class Tenant extends Person {
public Tenant(String name, Mediator mediator) {
super(name, mediator);
}
// 和中介沟通的方法
public void constact(String message) {
mediator.constact(message, this);
}
// 获取信息的方法
public void getMessage(String message) {
System.out.println("租房者" + name + "获取到的信息是" + message);
}
}
/**
* 房主类
*/
public class HouseOwner extends Person{
public HouseOwner(String name, Mediator mediator) {
super(name, mediator);
}
// 和中介沟通的方法
public void constact(String message) {
mediator.constact(message, this);
}
// 获取信息的方法
public void getMessage(String message) {
System.out.println("房主" + name + "获取到的信息是" + message);
}
}
public class Test01 {
public static void main(String[] args) {
// 创建中介者对象
MediatorStructure mediatorStructure = new MediatorStructure();
// 创建租房者对象
Tenant tenant = new Tenant("张三", mediatorStructure);
// 创建房主对象
HouseOwner houseOwner = new HouseOwner("李四", mediatorStructure);
// 中介要知道具体的房主和租客
mediatorStructure.setTenant(tenant);
mediatorStructure.setHouseOwner(houseOwner);
// 租客和房主都是通过中介来获取的信息、并进行沟通
tenant.constact("我想租一个两室一厅");
houseOwner.constact("2500一个月,年租2万5");
}
}