es6 语法学习 - 外观模式
一、基本概念
外观设计模式(Facade Pattern)是一种结构型设计模式,它为子系统中的一组接口提供了一个统一的高层接口,从而使得子系统更加容易使用。
二、 优点
- 简化使用:提供一个简单的接口,减少了与复杂子系统交互时的复杂度。
- 解耦:通过引入外观,客户端和系统的内部实现解耦,使得系统的内部变化对外部影响最小。
- 易于维护:由于外观模式将复杂性隐藏起来,系统更易于理解和维护。
三、缺点
- 不符合开闭原则:如果需要扩展系统功能,外观可能需要修改。
- 掩盖系统的复杂性:如果外观接口过于简单,可能会使得用户忽视系统的强大功能。
四、使用场景
- 当需要一个简单的接口来访问复杂系统时。
- 当需要对多个模块或类进行组合时,以减少直接的依赖关系。
- 当希望分离外部代码与系统内部实现时。
五、示例代码
以下是一个使用 JavaScript ES6 实现外观设计模式的示例。在这个示例中,我们创建一个家庭影院系统,包含多个子系统如 DVD 播放器、音响和投影仪。外观类将这些子系统的操作封装起来。
// 子系统 - DVD 播放器
class DVDPlayer {
on() {
console.log('DVD 播放器开机');
}
play(movie) {
console.log(`播放电影: ${movie}`);
}
off() {
console.log('DVD 播放器关机');
}
}
// 子系统 - 音响
class SoundSystem {
on() {
console.log('音响开机');
}
setVolume(volume) {
console.log(`音量设置为: ${volume}`);
}
off() {
console.log('音响关机');
}
}
// 子系统 - 投影仪
class Projector {
on() {
console.log('投影仪开机');
}
setInput(input) {
console.log(`设置投影仪输入为: ${input}`);
}
off() {
console.log('投影仪关机');
}
}
// 外观类
class HomeTheaterFacade {
constructor(dvdPlayer, soundSystem, projector) {
this.dvdPlayer = dvdPlayer;
this.soundSystem = soundSystem;
this.projector = projector;
}
watchMovie(movie) {
console.log('准备观看电影...');
this.projector.on();
this.projector.setInput('DVD');
this.soundSystem.on();
this.soundSystem.setVolume(5);
this.dvdPlayer.on();
this.dvdPlayer.play(movie);
}
endMovie() {
console.log('结束观看电影...');
this.dvdPlayer.off();
this.soundSystem.off();
this.projector.off();
}
}
// 使用示例
const dvdPlayer = new DVDPlayer();
const soundSystem = new SoundSystem();
const projector = new Projector();
const homeTheater = new HomeTheaterFacade(dvdPlayer, soundSystem, projector);
// 通过外观类观看电影
homeTheater.watchMovie('复仇者联盟');
homeTheater.endMovie();