java设计模式之外观模式(门面模式)
一、概念介绍
外观模式(Facade),他隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。这种类型的设计模式属于结构性模式。为子系统中的一组接口提供了一个统一的访问接口,这个接口使得子系统更容易被访问或者使用。
二、角色及使用场景
简单来说,该模式就是把一些复杂的流程封装成一个接口供给外部用户更简单的使用。这个模式中,设计到3个角色。
1).门面角色:外观模式的核心。它被客户角色调用,它熟悉子系统的功能。内部根据客户角色的需求预定了几种功能的组合。
2).子系统角色:实现了子系统的功能。它对客户角色和Facade时未知的。它内部可以有系统内的相互交互,也可以由供外界调用的接口。
3).客户角色:通过调用Facede来完成要实现的功能。
使用场景:
1- 为复杂的模块或子系统提供外界访问的模块;
2- 子系统相互独立;
3- 在层析结构中,可以使用外观模式定义系统的每一层的入口。
三、案例
下面,我们就通过一个简单的例子来实现该模式。
每个Computer都有CPU、Memory、Disk。在Computer开启和关闭的时候,相应的部件也会开启和关闭,所以,使用了该外观模式后,会使用户和部件之间解耦。如:
包体创建:
代码实现:
- 1、子系统类
/**
* cpu子系统类
*/
public class CPU {
public void start(){
System.out.println("cup is starting......");
}
public void shutDown(){
System.out.println("cup is shutDown......");
}
}
/**
* Disk子系统类
*/
public class Disk {
public void start(){
System.out.println("Disk is starting......");
}
public void shutDown(){
System.out.println("Disk is shutDown......");
}
}
/**
* Memory子系统类
*/
public class Memory {
public void start(){
System.out.println("memory is starting......");
}
public void shutDown(){
System.out.println("memory is shutDown......");
}
}
- 2、门面类
/**
* 门面类(核心)
*/
public class Computer {
private CPU cpu;
private Memory memory;
private Disk disk;
public Computer(){
cpu = new CPU();
memory = new Memory();
disk = new Disk();
}
public void start(){
System.out.println("computer start begin.....");
cpu.start();
memory.start();
disk.start();
System.out.println("computer start end.....");
}
public void shutDown(){
System.out.println("computer shutDown begin.....");
cpu.start();
memory.start();
disk.start();
System.out.println("computer shutDown end.....");
}
}
- 3、客户角色
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
computer.start();
System.out.println("--------------------------");
computer.shutDown();
}
}
- 4、运行结果
computer start begin.....
cup is starting......
memory is starting......
Disk is starting......
computer start end.....
--------------------------
computer shutDown begin.....
cup is starting......
memory is starting......
Disk is starting......
computer shutDown end.....
从上面的实例来看,有了这个Facade类,也就是Computer类,用户就不用亲自去调用子系统中的Disk,Memory、CPU类了,不需要知道系统内部的实现细节,甚至都不用知道系统内部的构成。客户端只需要跟Facade交互就可以了。
四、优点
-
松散耦合
门面模式松散了客户端与子系统的耦合关系,让子系统内部的模块能更容易扩展和维护。 -
简单易用
门面模式让子系统更加易用,客户端不再需要了解子系统内部的实现,也不需要跟众多子系统内部的模块进行交互,只需要跟门面类交互就可以了 -
更好的划分访问层次
通过合理使用Facade,可以帮助我们更好地划分访问的层次。有些方法是对系统外的,有些方法是系统内部使用的。把需要暴露给外部的功能集中到门面中,这样既方便客户端使用,也很好地隐藏了内部的细节。