中介者模式是什么?
中介者模式用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式封装了对象之间的通信。对象不再直接通信,而是通过中介者通信。
中介者模式的示例
下面以飞机着陆为例说明Mediator的应用,在例子中,飞机和跑道不直接通信,而是通过mediator处理。
public interface IATCMediator {
public void registerRunway(Runway runway);
public void registerFlight(Flight flight);
public boolean isLandingOk();
public void setLandingStatus(boolean status);
}
public class ATCMediator implements IATCMediator {
private Flight flight;
private Runway runway;
public boolean land;
public void registerRunway(Runway runway) {
this.runway = runway;
}
public void registerFlight(Flight flight) {
this.flight = flight;
}
public boolean isLandingOk() {
return land;
}
@Override
public void setLandingStatus(boolean status) {
land = status;
}
}
public interface Command {
void land();
}
public class Flight implements Command {
private IATCMediator atcMediator;
public Flight(IATCMediator atcMediator) {
this.atcMediator = atcMediator;
}
public void land() {
if (atcMediator.isLandingOk()) {
System.out.println("Landing done....");
atcMediator.setLandingStatus(true);
} else
System.out.println("Will wait to land....");
}
public void getReady() {
System.out.println("Getting ready...");
}
}
public class Runway implements Command {
private IATCMediator atcMediator;
public Runway(IATCMediator atcMediator) {
this.atcMediator = atcMediator;
atcMediator.setLandingStatus(true);
}
@Override
public void land() {
System.out.println("Landing permission granted...");
atcMediator.setLandingStatus(true);
}
}
public class MediatorDesignPattern {
public static void main(String args[]) {
IATCMediator atcMediator = new ATCMediator();
Flight sparrow101 = new Flight(atcMediator);
Runway mainRunway = new Runway(atcMediator);
atcMediator.registerFlight(sparrow101);
atcMediator.registerRunway(mainRunway);
sparrow101.getReady();
mainRunway.land();
sparrow101.land();
}
}
链接:http://javapapers.com/design-patterns/mediator-design-pattern/