9、外观模式(Facade)

来源:互联网 发布:burpsuite mac破解版 编辑:程序博客网 时间:2024/05/29 18:47

9、外观模式(Facade)

外观模式是为了解决类与类之家的依赖关系的,像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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class CPU {
   
 publicvoidstartup(){
  System.out.println("cpu startup!");
 }
   
 publicvoidshutdown(){
  System.out.println("cpu shutdown!");
 }
}
 
public class Memory {
   
 publicvoidstartup(){
  System.out.println("memory startup!");
 }
   
 publicvoidshutdown(){
  System.out.println("memory shutdown!");
 }
}
 
public class Disk {
   
 publicvoidstartup(){
  System.out.println("disk startup!");
 }
   
 publicvoidshutdown(){
  System.out.println("disk shutdown!");
 }
}
 
public class Computer {
 privateCPU cpu;
 privateMemory memory;
 privateDisk disk;
   
 publicComputer(){
  cpu =newCPU();
  memory =newMemory();
  disk =newDisk();
 }
   
 publicvoidstartup(){
  System.out.println("start the computer!");
  cpu.startup();
  memory.startup();
  disk.startup();
  System.out.println("start computer finished!");
 }
   
 publicvoidshutdown(){
  System.out.println("begin to close the computer!");
  cpu.shutdown();
  memory.shutdown();
  disk.shutdown();
  System.out.println("computer closed!");
 }
}

User类如下:

?
1
2
3
4
5
6
7
8
public class User {
  
 publicstaticvoid main(String[] args) {
  Computer computer =newComputer();
  computer.startup();
  computer.shutdown();
 }
}

输出:

start the computer!
cpu startup!
memory startup!
disk startup!
start computer finished!
begin to close the computer!
cpu shutdown!
memory shutdown!
disk shutdown!
computer closed!

如果我们没有Computer类,那么,CPU、Memory、Disk他们之间将会相互持有实例,产生关系,这样会造成严重的依赖,修改一个类,可能会带来其他类的修改,这不是我们想要看到的,有了Computer类,他们之间的关系被放在了Computer类里,这样就起到了解耦的作用,这,就是外观模式!

原创粉丝点击