public class Test {
public static void main(String[] args) {
Middleman middleman = new Middleman();
Landlord landlord = new Landlord("阿祖", middleman);
middleman.setLandlord(landlord);
Tenant tenant = new Tenant("阿伟", middleman);
middleman.setTenant(tenant);
// 房东依赖中介者 由中介者去传递消息给房东
landlord.communicate("我要出租房子");
// 租客依赖中介者 由中介者去传递消息给房东
tenant.communicate("我要找房子");
}
}
// 抽象中介者角色,与抽象同事者角色交互
abstract class AbstractMediator {
abstract void interactive(String message, AbstractPerson person);
}
// 抽象同事者类角色,聚合抽象中介者,留有交互方法
abstract class AbstractPerson {
protected String name;
protected AbstractMediator abstractMediator;
AbstractPerson(String name, AbstractMediator abstractMediator) {
this.abstractMediator = abstractMediator;
this.name = name;
}
// 与中介者沟通的方法
abstract void communicate(String message);
}
// 具体同事类角色 租客
class Tenant extends AbstractPerson {
Tenant(String name, AbstractMediator abstractMediator) {
super(name, abstractMediator);
}
@Override
void communicate(String message) {
// 告诉中介者我要干嘛(租房),由中介者去处理
abstractMediator.interactive(message, this);
}
void receive(String message) {
System.out.println("租客" + name + "获取到信息:" + message);
}
}
// 具体同事类 房东
class Landlord extends AbstractPerson {
Landlord(String name, AbstractMediator abstractMediator) {
super(name, abstractMediator);
}
@Override
void communicate(String message) {
// 告诉中介者我要干嘛(出租),由中介者去处理
abstractMediator.interactive(message, this);
}
void receive(String message) {
System.out.println("房东" + name + "获取到信息:" + message);
}
}
// 具体中介者
class Middleman extends AbstractMediator {
// 聚合具体同事类(根据业务,可以改成Map等)
private Tenant tenant;
private Landlord landlord;
// 让同事类进行交谈的地方(中介者交由同事类的具体业务代码出)
@Override
void interactive(String message, AbstractPerson person) {
if (tenant == person) {
landlord.receive(message);
} else if (landlord == person) {
tenant.receive(message);
}
}
public void setLandlord(Landlord landlord) {
this.landlord = landlord;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
}