简介
中介者模式时行为型模式的一种,在生活中也比较常见。当我们去租房时,链家就是中介者角色,房东在它那里发布房源信息,房客去链家寻找房源。下面就以房东发布房源和房客寻找房源为例来示例。
Demo示例
1.定义房产中介接口,然后链家实现该接口。
public interface HouseMediator {
void sendRentInfo(Client client, String info);
}
public class Lianjia implements HouseMediator{
@Override
public void sendRentInfo(Client client, String info) {
System.out.println(client.getRole() + " send info: " + info);
}
}
2.定义客户,对于链家,房东和房客均为其客户。
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Client {
private String role;
private HouseMediator mediator;
public void printRoomInfo(String info) {
this.mediator.sendRentInfo(this, info);
}
}
3.客户端调用
public class Test {
public static void main(String[] args) {
HouseMediator lianjia = new Lianjia();
Client houseOwner = new Client("House owner", lianjia);
Client tenant = new Client("Tenant", lianjia);
houseOwner.printRoomInfo("I want to rent my house.");
tenant.printRoomInfo("I want to rent a house");
/**
* House owner send info: I want to rent my house.
* Tenant send info: I want to rent a house
*/
}
}