设计模式有一条是;最小知道原则。就是说。用户知道的越少越好。
外观模式就是解决这个问题,将一些繁琐的工作放在一个具体类中通过调用这个方法实现调用
外观模式实例与解析
实例一:电源总开关
• 现在考察一个电源总开关的例子,以便进一步说明外观模式。为了使用方便,一个电源总开关可以控制四盏灯、一个风扇、一台空调和一台电视机的启动和关闭。通过该电源总开关可以同时控制上述所有电器设备,使用外观模式设计该系统。
//外观角色类 2 public class GeneralSwitchFacade { 3 private Light lights[]=new Light[4]; 4 private Fan fan; 5 private AirConditioner ac; 6 private Television tv; 7 8 public GeneralSwitchFacade() 9 { 10 lights[0]=new Light("左前"); 11 lights[1]=new Light("右前"); 12 lights[2]=new Light("左后"); 13 lights[3]=new Light("右后"); 14 fan=new Fan(); 15 ac=new AirConditioner(); 16 tv=new Television(); 17 } 18 19 public void on() 20 { 21 lights[0].on(); 22 lights[1].on(); 23 lights[2].on(); 24 lights[3].on(); 25 fan.on(); 26 ac.on(); 27 tv.on(); 28 } 29 30 public void off() 31 { 32 lights[0].off(); 33 lights[1].off(); 34 lights[2].off(); 35 lights[3].off(); 36 fan.off(); 37 ac.off(); 38 tv.off(); 39 } 40 } 41 42 //子系统角色类 43 public class Light 44 { 45 private String position; 46 47 public Light(String position) 48 { 49 this.position=position; 50 } 51 52 public void on() 53 { 54 System.out.println(this.position + "灯打开!"); 55 } 56 57 public void off() 58 { 59 System.out.println(this.position + "灯关闭!"); 60 } 61 } 62 63 //子系统角色 64 public class Fan 65 { 66 public void on() 67 { 68 System.out.println("风扇打开!"); 69 } 70 71 public void off() 72 { 73 System.out.println("风扇关闭!"); 74 } 75 } 76 77 //子系统角色 78 public class AirConditioner 79 { 80 public void on() 81 { 82 System.out.println("空调打开!"); 83 } 84 85 public void off() 86 { 87 System.out.println("空调关闭!"); 88 } 89 } 90 91 //子系统角色 92 public class Television 93 { 94 public void on() 95 { 96 System.out.println("电视机打开!"); 97 } 98 99 public void off() 100 { 101 System.out.println("电视机关闭!"); 102 } 103 } 104 105 //客户端 106 public class Client 107 { 108 public static void main(String args[]) 109 { 110 GeneralSwitchFacade gsf=new GeneralSwitchFacade(); 111 gsf.on(); 112 System.out.println("-----------------------"); 113 gsf.off(); 114 } 115 }