/**抽象同事类Colleague,同事类之间必须通过中介者才能进行消息传递*/
public abstract class Colleage {
protected String name;
protected Mediator mediator;
Colleage(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
/**与中介者联系*/
public abstract void constact(String message);
/**获取信息 */
public abstract void getMessage(String message);
}
//房东,具体同事类******************************************************************************************
class HouseOwner extends Colleage {
HouseOwner(String name, Mediator mediator) {
super(name, mediator);
}
@Override
public void constact(String message) {
mediator.constact(message, this);//需要与其他同事对象交互时,就通知中介对象,中介对象会负责后续的交互
}
@Override
public void getMessage(String message) {
System.out.println("房主" + name + "收到中介发的消息:\n " + message);
}
}
//房客******************************************************************************************
class Tenant extends Colleage {
Tenant(String name, Mediator mediator) {
super(name, mediator);
}
/**与中介者联系*/
@Override
public void constact(String message) {
mediator.constact(message, this);
}
/**获取信息*/
@Override
public void getMessage(String message) {
System.out.println("租房者" + name + "收到中介发的消息:\n " + message);
}
}
/**抽象中介者,定义好【同事类对象】到【中介者对象】的接口,用于各个【同事类之间】的通信。在里面定义了各个同事之间相互交互所需要的方法 */
public abstract class Mediator {
/**申明一个房东和租客之间联络的方法*/
public abstract void constact(String message, Colleage colleage);
}
/**具体中介者,实现抽象中介者中定义的方法,它需要维护每个同事对象,并负责具体的协调各个同事对象的交互关系*/
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, Colleage colleage) {
if (colleage == houseOwner) tenant.getMessage("你好,我是中介,我收到房东" + tenant.name + "的出租消息,内容为【" + message + "】");
else houseOwner.getMessage("你好,我是中介,我收到房客" + colleage.name + "的求租消息,内容为【" + message + "】");
}
}
public class Test {
public static void main(String[] args) {
//一个房主、一个租房者、一个中介机构
MediatorStructure mediator = new MediatorStructure();
//房主和租房者只需要知道中介机构即可
HouseOwner houseOwner = new HouseOwner("煞笔", mediator);
Tenant tenant = new Tenant("包青天", mediator);
//中介结构要知道房主和租房者
mediator.setHouseOwner(houseOwner);
mediator.setTenant(tenant);
tenant.constact("黑中介你好,请问你那里有没有二室一厅的房要出租?");
houseOwner.constact("有的,房租只要8000一月,很便宜吧!");
tenant.constact("滚粗");
houseOwner.constact("呵呵,还有一间一室一厅的房子,只要200块,要租不?");
tenant.constact("滚蛋");
}
}