c++ 门面模式(Facade)
门面模式是比较常用的一种设计模式,我们可能在无意中就会使用,门面模式就是用一个门面类来处理子系统的复杂关系,门面类简单的Api接口供客户端调用。用一个简单的演播室来表示。
#include <iostream> using namespace std; //class Camera; //class Light; //class Screen; class Camera { public: Camera() { } ~Camera() { } void TrunOn() { cout << "摄像机打开!" << endl; } void TrunOff() { cout << "摄像机关闭!" << endl; } void Rotate(int degrees) { cout << "Rotate the camera by "<<degrees<< "degrees!" <<endl; } }; class Light { public: Light() { } ~Light() { } void TrunOn() { cout << "灯光打开!" << endl; } void TrunOff() { cout << "灯光关闭!" << endl; } }; class Screen { public: Screen() { } ~Screen() { } void TrunOn() { cout << "显示器打开!" << endl; } void TrunOff() { cout << "显示器关闭!" << endl; } }; class Facade { public: Facade() { m_camera = new Camera(); m_lights = new Light(); m_Screen = new Screen(); } ~Facade() { delete m_camera; delete m_lights; delete m_Screen; } void Activate() { cout<< "激活设备开始直播!"<<endl; m_camera->TrunOn(); m_camera->Rotate(90); m_lights->TrunOn(); m_Screen->TrunOn(); } void Deactivate() { cout << "关闭设备!" << endl; m_camera->TrunOff(); m_camera->Rotate(0); m_lights->TrunOff(); m_Screen->TrunOff(); } private: Camera *m_camera; Light *m_lights; Screen *m_Screen; };
主函数:
int main() { Facade * m_facade = new Facade(); m_facade->Activate(); std::cout << "直播中!" << std::endl; m_facade->Deactivate(); getchar(); return 0; }
输出结果:
激活设备开始直播! 摄像机打开! Rotate the camera by 90degrees! 灯光打开! 显示器打开! 直播中! 关闭设备! 摄像机关闭! Rotate the camera by 0degrees! 灯光关闭! 显示器关闭!
如果不使用门面类的话,每一个客户端都要直接去调用设备,会客户端的代码很复杂。可读性差。