Facade Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.
门面模式中一个子系统的外部与其内部的通信可以通过一个统一的门面(Facade)对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。门面对象结合了完成特定行为所需要的各个子系统的方法,使Client其可以轻松执行该行为,而不考虑执行的子系统细节。
定义子系统:
public class SubsystemA {
public void doSomething() {
// do something
}
}
public class SubsystemB {
public void doSomething() {
// do something
}
}
定义Facade:
public class Facade {
SubsystemA systemA;
SubsystemB systemB;
public Facade(SubsystemA systemA, SubsystemB systemB) {
this.systemA = systemA;
this.systemB = systemB;
}
public void doSomething() {
systemA.doSomething();
systemB.doSomething();
}
}
定义Client:
public class Client {
public static void main(String[] args) {
Client client = new Client();
SubsystemA systemA = new SubsystemA();
SubsystemB systemB = new SubsystemB();
Facade facade = new Facade(systemA, systemB);
facade.doSomething();
}
}
Design Principle:
Principle of Least Knowledge: talk only to your immediate friends.
Invoke methods that belong to:
The object itself.
Objects passed in as a parameter to the method
Any object the method creates or instantiates
Any components of the object.
Not to call methods on objects that were returned from calling other method.
Without Principle:
public float getTemp() {
Thermometer thermometer = station.getThermometer();
return thermometer.getTemperature();
With Principle:
public float getTemp() {
return station.getTemperature();
}
像System.out.println()是违反这个设计原则的。它使用了System.out的返回值,在此基础上继续调用println。
应用:家庭影院,医院