概念
- 定义: 用一个中介对象封装一系列的对象交互,使各个对象不需要显示的相互作用,从而使其耦合松散,而且可以独立的改变它们之间的交互
- 优点: 减少类之间的以来,降低了类之间的耦合
- 缺点:同事类越多,中介者的逻辑越复杂,中介者会膨胀的很大
- 使用场景:中介者模式适用于多个对象之间紧密耦合的情况,紧密耦合的标准是:在类图中出现了蜘蛛网状结构,中介者模式有利于将蜘蛛网状结构转化为星型结构,使原本复杂魂落的逻辑变得清洗简单
代码实现
public abstract class AbstractMediator {
protected Landlord landlord;
protected Renter renter;
public AbstractMediator(Landlord landlord, Renter renter) {
this.landlord = landlord;
this.renter = renter;
}
public abstract void operate(String type, int number);
}
public class Mediator extends AbstractMediator {
public Mediator(Landlord landlord, Renter renter) {
super(landlord, renter);
}
@Override
public void operate(String type, int number) {
if (StringUtils.equals(type, "pay")) {
super.landlord.collect(number);
} else if (StringUtils.equals(type, "collect")) {
super.renter.pay(number);
}
}
}
public class Landlord {
public void collect(int number, AbstractMediator mediator) {
collect(number);
mediator.operate("collect", number);
}
public void collect(int number) {
System.out.println("landlord collect $" + number);
}
}
public class Renter {
public void pay(int number, AbstractMediator mediator) {
pay(number);
mediator.operate("pay", number);
}
public void pay(int number) {
System.out.println("Renter pay $" + number);
}
}
public class Client {
public static void main(String[] args) {
Landlord landlord = new Landlord();
Renter renter = new Renter();
AbstractMediator mediator = new Mediator(landlord, renter);
System.out.println("First month,Landlord collect rent of house");
landlord.collect(1000, mediator);
System.out.println("Second month, Renter pay rent of house");
renter.pay(1000, mediator);
}
}