JavaScript设计模式 -- 外观模式

发布于:2025-02-25 ⋅ 阅读:(16) ⋅ 点赞:(0)

外观模式(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}`);

    }

}

2. 创建外观类

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");

    }

}

3. 使用外观类

const facade = new HomeAutomationFacade();

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

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

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