一、定义:
门面模式(Facade Pattern
),是指提供一个统一的接口去访问多个子系统的多个不同的接口,它为子系统中的一组接口提供一个统一的高层接口。使得子系统更容易使用。
二、门面模式的作用:
参考文章:
The facade pattern (also spelled façade) is a software-design pattern commonly used with object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code. A facade can:
1、improve the readability and usability of a software library by masking interaction with more complex components behind a single (and often simplified) API;
2、provide a context-specific interface to more generic functionality (complete with context-specific input validation);
3、serve as a launching point for a broader refactor of monolithic or tightly-coupled systems in favor of more loosely-coupled code;
Developers often use the facade design pattern when a system is very complex or difficult to understand because the system has a large number of interdependent classes or because its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class that contains a set of members required by the client. These members access the system on behalf of the facade client and hide the implementation details.
简而言之就是门面模式主要有三个作用:
提高了可读性和可用性,屏蔽系统内部复杂的逻辑;
提供了一个更通用的接口;
支持更多松散耦合代码;
三、UML图:
客户端的调用变得非常简单明了。
四、设计模式使用实例:
1、设计组成一台电脑的各个组件:
/*
* 电脑CPU
*/
public class CPU {
public void freeze() {
//...
}
public void jump(long position) {
//...
}
public void execute() {
//...}
}
}
/*
* 硬件驱动
*/
class HardDrive {
public byte[] read(long lba, int size) {
//...
}
}
/*
* 内存
*/
class Memory {
public void load(long position, byte[] data) { ... }
}
2、抽取一个门面接口,便于扩展(不仅仅在于电脑的启动,手机和Pad亦然如此)
/*
* 抽取一个门面接口
*/
interface IComputerFacede{
public void start();
}
3、实现真正被客户端调用的门面对象
/*
* 门面对象
*/
class ComputerFacade implements IComputerFacede {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public ComputerFacade() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
public void start() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}
4、客户端调用
/*
* 客户端调用
*/
class Client {
/* 只要简单的一个调用,就可以完成电脑的启动,无需了解内部逻辑 */
public static void main(String[] args) {
ComputerFacade computer = new ComputerFacade();
computer.start();
}
}