外观模式类似迪米特法则,外观模式旨在将复杂的操作转化为一个接口给用户调用,省去了客户端细节的代码编写,以下的功能是存在三种模式,可选择开启或关闭,实现每一种功能需要开关不同的模式,如果将这些代码交给客户端编写,会有些麻烦,不如直接把一系列操作封装成一个类并提供接口:
cpp
class mode1
{
public:
void on()
{
cout << "开启" << endl;
}
void off()
{
cout << "关闭" << endl;
}
};
class mode2
{
public:
void on()
{
cout << "开启" << endl;
}
void off()
{
cout << "关闭" << endl;
}
};
class mode3
{
public:
void on()
{
cout << "开启" << endl;
}
void off()
{
cout << "关闭" << endl;
}
};
class One_click_mode
{
public:
void start()
{
m1->on();
m2->off();
m3->on();
}
~One_click_mode()
{
delete m1;
delete m2;
delete m3;
}
private:
mode1* m1 = new mode1;
mode2* m2 = new mode2;
mode3* m3 = new mode3;
};
void test()
{
One_click_mode* ocm = new One_click_mode;
ocm->start();
}
int main()
{
test();
return 0;
}