外观模式

最后更新于:2022-04-01 20:29:32

## 模式定义: 外观模式提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。 ## 模式结构: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-30_57c545909cbf5.jpg) ## 举例: 构造一个家庭影院,当启动watchMovie方法时可以看电影,当使用endMovie时关闭电影。 ## 编程实现及执行结果: ~~~ #include using namespace std; //组件类 class Amplifier { public: void on() { cout << "Amplifier on" << endl; } void off() { cout << "Amplifier off" << endl; } }; class Tuner { public: void on() { cout << "Tuner on" << endl; } void off() { cout << "Tuner off" << endl; } }; class DvdPlayer { public: void on() { cout << "DvdPlayer on" << endl; } void off() { cout << "DvdPlayer off" << endl; } }; class Screen { public: void on() { cout << "Screen on" << endl; } void off() { cout << "Screen off" << endl; } }; //家庭影院 class HomeTheaterFacade { public: //统一接口 void watchMovie() { amp.on(); tuner.on(); dvd.on(); screen.on(); } void endMovie() { amp.off(); tuner.off(); dvd.off(); screen.off(); } HomeTheaterFacade(Amplifier am, Tuner tune, DvdPlayer dv, Screen scree) { amp = am; tuner = tune; dvd = dv; screen = scree; } //~HomeTheaterFacade(){} private: Amplifier amp; Tuner tuner; DvdPlayer dvd; Screen screen; }; //客户代码 int main() { Amplifier amp; Tuner tuner; DvdPlayer dvd; Screen screen; HomeTheaterFacade homeTheaterFacade(amp,tuner,dvd,screen);; homeTheaterFacade.watchMovie(); homeTheaterFacade.endMovie(); return 0; } ~~~ 执行结果: **Amplifieron** **Tuneron** **DvdPlayeron** **Screenon** **Amplifieroff** **Tuneroff** **DvdPlayeroff** **Screenoff** **请按任意键继续. . .** ## 设计原则: 最少知识原则:只和你的密友谈话
';