码迷,mamicode.com
首页 > 其他好文 > 详细

外观模式-Facade

时间:2016-11-05 22:38:04      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:作用   public   耦合度   tin   static   out   close   cad   .sh   

外观模式是为了解决类与类之间依赖关系的,外观模式将类间关系放在一个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

标签:作用   public   耦合度   tin   static   out   close   cad   .sh   

原文地址:http://www.cnblogs.com/joshua-aw/p/6033987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!