外观模式 📖
定义
外观模式(Facade Pattern),是指提供一个统一的接口去访问多个子系统的多个不同的接口,为子系统中的一组接口提供统一的高层接口。使得子系统更容易使用,不仅简化类中的接口,而且实现调用者和接口的解耦。
洗衣机的一链洗衣按钮,包含浸泡、洗衣、漂洗、脱水,就是一个外观。
实现
js
class Light {
turnOn() {
console.log('Light turn on')
}
turnOff() {
console.log('Light turn off')
}
}
class TV {
turnOn() {
console.log('TV turn on')
}
turnOff() {
console.log('TV turn off')
}
}
class Computer {
turnOn() {
console.log('Computer turn on')
}
turnOff() {
console.log('Computer turn off')
}
}
class Facade {
constructor() {
this.light = new Light()
this.tv = new TV()
this.computer = new Computer()
}
turnOn() {
this.light.turnOn()
this.tv.turnOn()
this.computer.turnOn()
}
turnOff() {
this.light.turnOff()
this.tv.turnOff()
this.computer.turnOff()
}
}
const facade = new Facade()
facade.turnOn()
facade.turnOff()