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

本文深入探讨了门面模式的概念,通过类图展示了其在简化系统接口方面的应用,并提供了具体的代码实现,帮助开发者理解如何利用门面模式提高系统易用性和减少耦合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.含义

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

 

2.类图

不使用门面模式的设计


 

使用门面模式的设计

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值