Featured image of post Java设计模式-中介者模式Mediator

Java设计模式-中介者模式Mediator

相关文章

【合集】Java设计模式

中介者模式

中介者

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static abstract class Mediator {
    public abstract void contact(String message, Person person);
}
@EqualsAndHashCode(callSuper = true)
@Data
public static class MediatorStructure extends Mediator {
    private HouseOwner houseOwner;
    private Tenant tenant;
    public void contact(String message, Person person) {
        if (person == houseOwner) {
            tenant.getMessage(message);
        } else {
            houseOwner.getMessage(message);
        }
    }
}

同事类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@AllArgsConstructor
public static abstract class Person {
    protected String name;
    protected Mediator mediator;
}
public static class HouseOwner extends Person {
    public HouseOwner(String name, Mediator mediator) {
        super(name, mediator);
    }
    public void contact(String message) {
        mediator.contact(message, this);
    }
    public void getMessage(String message) {
        System.out.println("房主" + name + "获取到的信息是:" + message);
    }
}
public static class Tenant extends Person {
    public Tenant(String name, Mediator mediator) {
        super(name, mediator);
    }
    public void contact(String message) {
        mediator.contact(message, this);
    }
    public void getMessage(String message) {
        System.out.println("租房者" + name + "获取到的信息是:" + message);
    }
}

客户端调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
MediatorStructure mediator = new MediatorStructure();

Tenant tenant = new Tenant("李四", mediator);
mediator.setTenant(tenant);

HouseOwner houseOwner = new HouseOwner("张三", mediator);
mediator.setHouseOwner(houseOwner);

tenant.contact("我要租三室的房子!!!");
houseOwner.contact("我这里有三室的房子,你要租吗?");

输出

1
2
房主张三获取到的信息是:我要租三室的房子!!!
租房者李四获取到的信息是:我这里有三室的房子,你要租吗?
皖ICP备2024056275号-1
发表了78篇文章 · 总计148.99k字
本站已稳定运行