介绍Java 门面模式
本文我们探讨一种结构模式————门面模式(Facade)。首先我们概要介绍,阐述其优点及能够解决什么问题。然后应用该模式至java中实际存在的问题。
什么是门面模式
简言之,门面把复杂系统封装成简单接口,隐藏起复杂性,使其他子系统更简单地使用。同时如果需要直接使用复杂子系统,仍然可以。其不强制任何时间都使用。
使用该模式除了更简化的接口,也让客户端实现和复杂子系统进行解耦。因此,我们能够改变已经存在的子系统而不影响客户端。下面通过示例进行说明。
示例
假设我们想发动汽车,下面图示显示遗留系统的操作流程:
如图所示,相当复杂,正确启动引起需要一些周折。
airFlowController.takeAir()
fuelInjector.on()
fuelInjector.inject()
starter.start()
coolingController.setTemperatureUpperLimit(DEFAULT_COOLING_TEMP)
coolingController.run()
catalyticConverter.on()
停止引擎类似也需要一些步骤:
fuelInjector.off()
catalyticConverter.off()
coolingController.cool(MAX_ALLOWED_TEMP)
coolingController.stop()
airFlowController.off()
我们确实需要门面进行简化,我们通过startEngine() 和 stopEngine()两个方法隐藏所有复杂操作步骤。实现代码如下:
public class CarEngineFacade {
private static int DEFAULT_COOLING_TEMP = 90;
private static int MAX_ALLOWED_TEMP = 50;
private FuelInjector fuelInjector = new FuelInjector();
private AirFlowController airFlowController = new AirFlowController();
private Starter starter = new Starter();
private CoolingController coolingController = new CoolingController();
private CatalyticConverter catalyticConverter = new CatalyticConverter();
public void startEngine() {
fuelInjector.on();
airFlowController.takeAir();
fuelInjector.on();
fuelInjector.inject();
starter.start();
coolingController.setTemperatureUpperLimit(DEFAULT_COOLING_TEMP);
coolingController.run();
catalyticConverter.on();
}
public void stopEngine() {
fuelInjector.off();
catalyticConverter.off();
coolingController.cool(MAX_ALLOWED_TEMP);
coolingController.stop();
airFlowController.off();
}
}
现在,我们启动和停止汽车,仅需要两行代码,而不是13行:
facade.startEngine();
// ...
facade.stopEngine();
缺点
该模式并不强迫我们进行适当的权衡,因为它只添加了额外的抽象层。
有时在简单的场景中过度使用将导致冗余实现。
总结
本文我们探讨了门面模式,并演示如何在已知系统之上实现一个抽象层,用于简化对子系统的调用。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/89814784