1. 子系统角色
-
SubSystem(子系统角色):主板、内存、CPU、硬盘、操作系统
//SubSystem(子系统角色) //主板 class Motherboard { public: Motherboard() { std::cout << "Motherboard 构造函数" << std::endl; } ~Motherboard() { std::cout << "~Motherboard 析构函数" << std::endl; } void powerOnMotherboard() { std::cout << "------主板上电------" << std::endl; } private: }; //内存 class Memory { public: Memory() { std::cout << "Memory 构造函数" << std::endl; } ~Memory() { std::cout << "~Memory 析构函数" << std::endl; } void selfCheckMemory() { std::cout << "------内存自检电------" << std::endl; } private: }; //CPU class CPU { public: CPU() { std::cout << "CPU 构造函数" << std::endl; } ~CPU() { std::cout << "~CPU 析构函数" << std::endl; } void runCPU() { std::cout << "------CPU运行------" << std::endl; } private: }; //HardDisk class HardDisk { public: HardDisk() { std::cout << "HardDisk 构造函数" << std::endl; } ~HardDisk() { std::cout << "~HardDisk 析构函数" << std::endl; } void readHardDisk() { std::cout << "------读取硬盘------" << std::endl; } }; //OS class OS { public: OS() { std::cout << "OS 构造函数" << std::endl; } ~OS() { std::cout << "~OS 析构函数" << std::endl; } void loadOS() { std::cout << "------加载操作系统------" << std::endl; } private: };
2. 外观角色
-
Facade外观模式
//Facade(外观模式) class PowerOnButton { public: PowerOnButton() { std::cout << "PowerOnButton 构造函数" << std::endl; m_pMotherboard = new Motherboard; m_pMemory = new Memory; m_pCPU = new CPU; m_pHardDisk = new HardDisk; m_pOS = new OS; } ~PowerOnButton() { std::cout << "~PowerOnButton 析构函数函数" << std::endl; if (nullptr != m_pMotherboard) { delete m_pMotherboard; m_pMotherboard = nullptr; } if (nullptr != m_pMemory) { delete m_pMemory; m_pMemory = nullptr; } if (nullptr != m_pCPU) { delete m_pCPU; m_pCPU = nullptr; } if (nullptr != m_pHardDisk) { delete m_pHardDisk; m_pHardDisk = nullptr; } if (nullptr != m_pOS) { delete m_pOS; m_pOS = nullptr; } } void pressButton() { std::cout << std::endl; std::cout << "点击电源按钮..." << std::endl; std::cout << "正在开机..." << std::endl; std::cout << "...." << std::endl; std::cout << ".." << std::endl; m_pMotherboard->powerOnMotherboard(); m_pMemory->selfCheckMemory(); m_pCPU->runCPU(); m_pHardDisk->readHardDisk(); m_pOS->loadOS(); printf("开机完成!\n"); std::cout << std::endl; } private: Motherboard *m_pMotherboard; Memory *m_pMemory; CPU *m_pCPU; HardDisk *m_pHardDisk; OS *m_pOS; };
3. 主函数
#include <string> #include <sstream> using namespace std; void main() { auto *powerOnButton = new PowerOnButton(); powerOnButton->pressButton(); delete powerOnButton; system("pause"); }