外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
SubSystem.h:
#ifndef SUB_SYSTEM_H_
#define SUB_SYSTEM_H_
#include
// 内存
class Memory {
public:
Memory() {}
void selfCheck() {
std::cout << "内存自检中..." << std::endl;
std::cout << "内存自检完成!" << std::endl;
}
};
// 处理器
class Processor {
public:
Processor() {}
void run() {
std::cout << "启动CPU中..." << std::endl;
std::cout << "启动CPU成功!" << std::endl;
}
};
// 硬盘
class HardDisk {
public:
HardDisk() {}
void read() {
std::cout << "读取硬盘中..." << std::endl;
std::cout << "读取硬盘成功!" << std::endl;
}
};
// 操作系统
class OS {
public:
OS() {}
void load() {
std::cout << "载入操作系统中..." << std::endl;
std::cout << "载入操作系统成功!" << std::endl;
}
};
#endif // SUB_SYSTEM_H_
Facade.h:
#ifndef FACADE_H_
#define FACADE_H_
#include "SubSystem.h"
class ComputerOperator {
public:
ComputerOperator() {
memory_ = new Memory();
processor_ = new Processor();
hard_disk_ = new HardDisk();
os_ = new OS();
}
~ComputerOperator() {
delete memory_;
delete processor_;
delete hard_disk_;
delete os_;
memory_ = nullptr;
processor_ = nullptr;
hard_disk_ = nullptr;
os_ = nullptr;
}
void powerOn() {
std::cout << "正在开机..." << std::endl;
memory_->selfCheck();
processor_->run();
hard_disk_->read();
os_->load();
std::cout << "开机成功!" << std::endl;
}
private:
Memory* memory_;
Processor* processor_;
HardDisk* hard_disk_;
OS* os_;
};
#endif // FACADE_H_
main.cpp:
#include "Facade.h"
int main() {
system("chcp 65001");
ComputerOperator* computer_operator = new ComputerOperator();
computer_operator->powerOn();
delete computer_operator;
system("pause");
}
输出: