JavaScript设计模式 -- 外观模式

外观模式(Facade Pattern)是一种设计模式,用于为复杂的子系统提供一个简单的接口,以减少子系统间的依赖和复杂性。在 JavaScript 中实现外观模式,通常是为了提供一个统一的接口来简化客户端与多个子系统交互的过程。

外观模式的优点

简化接口:通过单一的接口隐藏了系统的复杂性,使得客户端使用更加简单。

减少依赖:降低了客户端与子系统之间的耦合度,因为客户端不需要直接与子系统交互。

提高安全性:可以在外观中加入访问控制,限制客户端对子系统的直接访问。

外观模式的结构

外观模式通常包含以下几个角色:

Facade(外观角色):为多个子系统对外提供一个共同的接口。

Subsystem(子系统角色):一系列紧密相关的类的集合,它们共同完成了一个特定的功能。

示例实现

假设我们有一个复杂的系统,包括一个灯光控制模块、一个空调控制模块和一个电视控制模块,我们可以创建一个外观类来简化这些模块的交互。

  1. 定义子系统

class Light {

turnOn() {

console.log("Light is on");

}

turnOff() {

console.log("Light is off");

}

}

class AirConditioner {

setTemperature(temp) {

console.log(`Air conditioner temperature set to ${temp}`);

}

}

class TV {

turnOn() {

console.log("TV is on");

}

turnOff() {

console.log("TV is off");

}

setChannel(channel) {

console.log(`TV channel set to ${channel}`);

}

}

  1. 创建外观类

class HomeAutomationFacade {

constructor() {

this.light = new Light();

this.airConditioner = new AirConditioner();

this.tv = new TV();

}

watchTV() {

this.tv.turnOn();

this.tv.setChannel(10); // 假设我们想看第10频道新闻。

console.log("Ready to watch TV");

}

sleep() {

this.tv.turnOff();

this.light.turnOff();

this.airConditioner.setTemperature(25); // 假设我们想设置空调温度为25度。

console.log("Preparing for sleep");

}

}

  1. 使用外观类

const facade = new HomeAutomationFacade();

facade.watchTV(); // 使用外观类简化操作电视的过程。

facade.sleep(); // 使用外观类简化准备睡觉的过程。

通过这种方式,客户端代码只需要与 HomeAutomationFacade 类交互,而不需要直接与 Light、AirConditioner 和 TV 类交互,从而简化了客户端代码并降低了系统的耦合度。这就是外观模式在 JavaScript 中的典型应用。

相关推荐
道友老李6 分钟前
【设计模式精讲】行为型模式之策略模式
设计模式·策略模式
我命由我123452 小时前
微信小程序 - 条件渲染(wx:if、hidden)与列表渲染(wx:for)
javascript·微信小程序·小程序·typescript·html·html5·js
天天向上10242 小时前
VSCode 使用import导入js/vue等时添加智能提示,并可跳转到定义
javascript·vue.js·vscode
七灵微3 小时前
【前端】Axios & AJAX & Fetch
前端·javascript·ajax
究极无敌暴龙战神X3 小时前
一篇文章学懂Vuex
前端·javascript·vue.js
程序员黄同学4 小时前
请谈谈 React 中的虚拟 DOM,如何通过 Diff 算法最小化真实DOM 更新次数?
javascript·算法·react.js
院人冲冲冲4 小时前
微前端qiankun打包部署
开发语言·前端·javascript
Winter_Bear5 小时前
vue移动端配置flexible.js
前端·javascript
亿点鸭梨6 小时前
如何在 UniApp 中集成激励奖励(流量主)
前端·javascript·vue.js·uni-app