外观模式应该是用的很多的一种模式,特别是当一个系统很复杂时,系统提供给客户的是一个简单的对外接口,而把里面复杂的结构都封装了起来。客户只需使用这些简单接口就能使用这个系统,而不需要关注内部复杂的结构。
#include <iostream>
using namespace std;
// 灯
class Light
{
public:
void on()
{
cout << "打开灯" << endl;
}
void off()
{
cout << "关灯" << endl;
}
};
// 插座
class Socket
{
public:
void on()
{
cout << "打开插座" << endl;
}
void off()
{
cout << "关闭插座" << endl;
}
};
// 音响
class Audio
{
public:
void on()
{
cout << "播放音乐" << endl;
}
void off()
{
cout << "关闭音乐" << endl;
}
};
// 天猫精灵
class TmallGenie
{
public:
TmallGenie()
{
pLight = new Light;
pSocket = new Socket;
pAudio = new Audio;
}
void HelloTimallGenie()
{
pLight->on();
pSocket->on();
pAudio->on();
}
void ByeTimallGenie()
{
pLight->off();
pSocket->off();
pAudio->off();
}
private:
Light* pLight;
Socket* pSocket;
Audio* pAudio;
};
void test_01()
{
TmallGenie* tmall = new TmallGenie;
cout << "你好,天猫精灵..." << endl;
tmall->HelloTimallGenie();
cout << "----------------" << endl;
cout << "天猫精灵,再见..." << endl;
tmall->ByeTimallGenie();
delete tmall;
}
int main()
{
test_01();
system("pause");
return 0;
}