门面模式:外部与一个子系统的通信必须通过一个统一的门面对象进行。
门面模式类似于适配器模式,但是门面模式并不包含具体的业务逻辑,门面模式是一个用来减少系统耦合,优化系统架构的接口
门面模式包括门面和子系统两个角色。门面模式提高了子系统的独立性和可移植性。
由于门面模式不包含具体的业务逻辑,这样的好处是子系统内部的逻辑修改了,不影响其他子系统的调用,对其他子系统是透明的。
客户端:
package com.javapatterns.facade.securityfacade; public class Client { private static SecurityFacade security = new SecurityFacade(); public static void main(String[] args) { security.activate(); } }
门面:
package com.javapatterns.facade.securityfacade; public class SecurityFacade { /** * @directed*/ private Camera camera1= new Camera(), camera2= new Camera(); /** * @directed */ private Light light1 = new Light(), light2 = new Light(), light3 = new Light(); /** * @directed*/ private Sensor sensor = new Sensor(); /** * @directed*/ private Alarm alarm = new Alarm(); public void activate() { camera1.turnOn(); camera2.turnOn(); light1.turnOn(); light2.turnOn(); light3.turnOn(); sensor.activate(); alarm.activate(); } public void deactivate() { camera1.turnOff(); camera2.turnOff(); light1.turnOff(); light2.turnOff(); light3.turnOff(); sensor.deactivate(); alarm.deactivate(); } }
内部系统组建1
package com.javapatterns.facade.securityfacade; public class Alarm { public void activate() { System.out.println("Activating the alarm."); } public void deactivate() { System.out.println("Deactivating the alarm."); } public void ring() { System.out.println("Ring the alarm."); } public void stopRing() { System.out.println("Stop the alarm."); } }
内部系统组建2
package com.javapatterns.facade.securityfacade; public class Camera { public void turnOn() { System.out.println("Turning on the camera."); } public void turnOff() { System.out.println("Turning off the camera."); } public void rotate(int degrees) { System.out.println("Rotating the camera by " + degrees + " degrees."); } }
内部系统组建3
package com.javapatterns.facade.securityfacade; public class Light { public void turnOn() { System.out.println("Turning on the light."); } public void turnOff() { System.out.println("Turning off the light."); } public void changeBulb() { System.out.println("Changing the light-bulb."); } }
内部系统组建4
package com.javapatterns.facade.securityfacade; public class Sensor { public void activate() { System.out.println("Activating on the sensor."); } public void deactivate() { System.out.println("Deactivating on the sensor."); } public void trigger() { System.out.println("The sensor has been triggered."); } }