首页 > 代码库 > 外观模式-Facade

外观模式-Facade

外观模式是为了解决类与类之间依赖关系的,外观模式将类间关系放在一个Facade类中,降低了类类之间的耦合度,该模式中不涉及接口

 

举一个经典的例子:

CPU类:

1 public class CPU {  
2     public void startup(){  
3         System.out.println("cpu startup");  
4     }  
5       
6     public void shutdown(){  
7         System.out.println("cpu shutdown");  
8     }  
9 }  

Mainboard类:

 1 public class Mainboard {  
 2       
 3     public void startup(){  
 4         System.out.println("mainboard startup");  
 5     }  
 6       
 7     public void shutdown(){  
 8         System.out.println("mainboard shutdown");  
 9     }  
10 } 

Disk类:

 1 public class Disk {  
 2       
 3     public void startup(){  
 4         System.out.println("disk startup");  
 5     }  
 6       
 7     public void shutdown(){  
 8         System.out.println("disk shutdown");  
 9     }  
10 } 

Computer类(外观类):

 1 public class Computer {  
 2     private CPU cpu;  
 3     private Mainboard mainboard;  
 4     private Disk disk;  
 5       
 6     public Computer(){  
 7         cpu = new CPU();  
 8         mainboard = new Mainboard();  
 9         disk = new Disk();  
10     }  
11       
12     public void startup(){  
13         System.out.println("starting the computer");  
14         cpu.startup();  
15         mainboard.startup();  
16         disk.startup();  
17         System.out.println("computer is started");  
18     }  
19       
20     public void shutdown(){  
21         System.out.println("closing the computer");  
22         disk.shutdown();  
23         mainboard.shutdown();  
24         cpu.shutdown();  
25         System.out.println("computer is closed");  
26     }  
27 } 

测试类:

1 public class Main {  
2 
3     public static void main(String[] args) {  
4         Computer computer = new Computer();  
5         computer.startup();  
6         computer.shutdown();  
7     }  
8 }

测试结果:

starting the computer
cpu startup
mainboard startup
disk startup
computer is started
closing the computer
disk shutdown
mainboard shutdown
cpu shutdown
computer is closed

 

如果我们没有外观类(Computer),CPU、Mainboard、Disk之间将会相互持有实例对象,造成严重的依赖;而有了Computer,他们之间的关系被放在了Computer类里,这样就起到了解耦的作用。这就是外观模式!

 

外观模式-Facade