定义
中介者模式(Mediator),作为中介者使得两个存在耦合关系的对象互不相干,将多对多的相互作用转化为一对多的相互作用。
实现
定义一个中介者抽象类:
public abstract class Mediator {
public abstract void exec(String command);
}
再定义一个持有中介者的抽象角色类,这里以房东和租客的例子展开:
public abstract class Role {
protected Mediator mediator;
public Role(Mediator mediator) {
this.mediator = mediator;
}
}
租客类:
public class Renter extends Role {
public Renter(Mediator mediator) {
super(mediator);
}
public void receive() {
System.out.println("租户收到新的可租信息");
}
public void requestRent() {
System.out.println("租户请求租房");
}
}
房东类:
public class Landlord extends Role {
public Landlord(Mediator mediator) {
super(mediator);
}
public void rentOut() {
System.out.println("房东发布出租信息");
}
public void receive() {
System.out.println("房东收到新的求租信息");
}
}
中介掌握了房东和租客的信息,并进行双向同步,其中介者的作用便展现了出来:
public class OneMediator extends Mediator {
private Landlord landlord;
private Renter renter;
public OneMediator() {
}
@Override
public void exec(String command) {
if (command.equals("landlord")) {
landlord.rentOut();
renter.receive();
} else if (command.equals("renter")) {
renter.requestRent();
landlord.receive();
}
}
public Landlord getLandlord() {
return landlord;
}
public void setLandlord(Landlord landlord) {
this.landlord = landlord;
}
public Renter getRenter() {
return renter;
}
public void setRenter(Renter renter) {
this.renter = renter;
}
}
public class Client {
public static void main(String[] args) {
OneMediator mediator = new OneMediator();
Landlord landlord = new Landlord(mediator);
Renter renter = new Renter(mediator);
mediator.setLandlord(landlord);
mediator.setRenter(renter);
mediator.exec("landlord");
mediator.exec("renter");
}
}
从例子中可以看出,中介者持有原本具有紧耦合的多对多关系的房东和租客,实现了两者的松耦合。通过中介者解决了这种复杂的网状关系,转而实现了以中介者为中心的星型结构,降低了系统复杂性,提高了可扩展性。
Android 源码中的中介者模式
public class KeyguardViewMediator extends SystemUI {
private AlarmManager mAlarmManager;
private AudioManager mAudioManager;
private StatusBarManager mStatusBarManager;
private boolean mSwitchingUser;
private boolean mSystemReady;
private boolean mBootCompleted;
/** High level access to the power manager for WakeLocks */
private PowerManager mPM;
/** High level access to the window manager for dismissing keyguard animation */
private IWindowManager mWM;
/** TrustManager for letting it know when we change visibility */
private TrustManager mTrustManager;
/** SearchManager for determining whether or not search assistant is available */
private SearchManager mSearchManager;
}
本文由
Fynn_ 原创,未经许可,不得转载!
网友评论