门面模式隐藏了一个任务的复杂性,提供吧一个简单的接口,一个很好的例子是电脑的启动,当一个电脑启动,他涉及CPU,内存,硬盘等等,为了使他对用户简单,我们添加一个门面来包裹这个任务的复杂性,并提供一个简单的接口代替。
1、门面模式的类图
2、Java门面模式的例子
//the components of a computer
class CPU {
public void processData() { }
}
class Memory {
public void load() { }
}
class HardDrive {
public void readdata() { }
}
/* Facade */
class Computer {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
public void run() {
cpu.processData();
memory.load();
hardDrive.readdata();
}
}
class User {
public static void main(String[] args) {
Computer computer = new Computer();
computer.run();
}
}
3、实际项目中的例子
在javax.faces.context中,ExternalContext内部使用ServletContext, HttpSession, HttpServletRequest, HttpServletResponse等等,他允许接口api自然地访问他们包含的应用变量。
以上文章翻译自: http://www.programcreek.com/2013/02/java-design-pattern-facade/