0%

外观模式

思想

即在一个容器类中持有多个其他类的实例对象;

容器类是作为一个外观,直接与其他类进行操作的,而内部持有的其他类不需要直接与其他类直接交互;

比如Computer是一个容器类,而CPU、内存等是其他目标类;

描述

为了解决类与类之家的依赖关系的,像spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口;

思想

即用给一个容器类(管理目标类的一个类)来管理或者实现多个目标类;

在类中有目标类变量;

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class CPU{
public void start(){
Test.printMsg("cpu start");
}
public void shutdown(){
Test.printMsg("cpu shutdown");
}
}
class Disk{
public void start(){
Test.printMsg("disk start");
}
public void shutdown(){
Test.printMsg("disk shutdown");
}
}
class Computer{
private CPU cpu;
private Disk disk;
public Computer(){
cpu = new CPU();
disk = new Disk();
}
public void start(){
cpu.start();
disk.start();
}
public void shutdown(){
cpu.shutdown();
disk.shutdown();
}
}
public class Test {
public static void printMsg(String msg){
System.out.println(msg);
}
public static void main(String[] args){
Computer computer = new Computer();
computer.start();
computer.shutdown();
}
}