10 结构模式 - 门面(Facade)模式

1.含义

外部与一个子系统的通信必须通过一个统一的门面对象进行,这就是门面模式。

 

2.类图

不使用门面模式的设计


10 结构模式 - 门面(Facade)模式

 

使用门面模式的设计
10 结构模式 - 门面(Facade)模式

3.代码

/*
 * 门面类
 */
public class SecurityFacade {
	private Camera camera1, camera2;
	private Light light1, light2, light3;
	private Sensor sensor;
	private Alarm alarm;

	public SecurityFacade() {
		camera1 = new Camera();
		camera2 = new Camera();
		light1 = new Light();
		light2 = new Light();
		light3 = new Light();
		sensor = new Sensor();
		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();
	}
}


/*
 * 照相机类
 */
public class Camera {
	public void turnOn() {
		S.s("Turning on the camera.");
	}
	public void turnOff() {
		S.s("Turning off the camera.");
	}
	public void rotate(int degrees) {
		S.s("rotating the camera by " + degrees+"degrees.");
	}
}


/*
 * 电灯类
 */
public class Light {
	public void turnOn() {
		S.s("Turning on the light.");
	}
	public void turnOff() {
		S.s("Turning off the light.");
	}
	public void changeBulb() {
		S.s("Changing the light bulb.");
	}
}


/*
 * 传感器类
 */
public class Sensor {
	public void activate() {
		S.s("Activating the sensor.");
	}
	public void deactivate() {
		S.s("Deactivating the sensor.");
	}
	public void trigger() {
		S.s("The sensor has been triggered.");
	}
}


/*
 * 警报类
 */
public class Alarm {
	public void activate() {
		S.s("Activating the alarm.");
	}

	public void deactivate() {
		S.s("Deactivate the alarm.");
	}

	public void ring() {
		S.s("Ring the alarm.");
	}

	public void stopRing() {
		S.s("Stop the alarm.");
	}
}


/*
 * 测试类
 */
public class Test {
	
	public static void main(String[] args) {
		SecurityFacade sf = new SecurityFacade();
		sf.activate();
		sf.deactivate();
	}
}
 

z

你可能感兴趣的:(Facade)