外观模式:
外观模式为子系统中的一组接口提供一个统一的入口。其定义了一个高层的接口,这个接口使得这一子系统更加容易使用。
在外观模式中,外部与一个或者多个子系统的通信,可以通过一个统一的外观对象来进行。
外观模式实例之电源总开关:
从类图我们可以看出,GSF类里面关联了lights、fan、ac、tv,并通过on()、off()来实现对他们的统一管理(进行打开和关闭)。
子系统类Light:
//子系统类Light
class Light{
public:
Light(string position){
this->position = position;
}
void on(){
cout << this->position << "灯打开!" << endl;
}
void off(){
cout << this->position << "灯关闭!" << endl;
}
private:
string position;
};
子系统类Fan:
//子系统类Fan
class Fan{
public:
void on(){
cout << "风扇打开!" << endl;
}
void off(){
cout << "风扇关闭!" << endl;
}
};
子系统类AirConditioner:
//子系统类AirConditioner
class AirConditioner{
public:
void on(){
cout << "空调打开!" << endl;
}
void off(){
cout << "空调关闭!" << endl;
}
};
子系统类Television:
//子系统类Television
class Television{
public:
void on(){
cout << "电视机打开!" << endl;
}
void off(){
cout << "电视机关闭!" << endl;
}
};
外观类GeneralSwitchFacade:
//外观类GeneralSwitchFacade
class GeneralSwitchFacade{
public:
GeneralSwitchFacade(){
lights.push_back(make_shared<Light>("左前"));
lights.push_back(make_shared<Light>("右前"));
lights.push_back(make_shared<Light>("左后"));
lights.push_back(make_shared<Light>("右后"));
fan = make_shared<Fan>();
ac = make_shared<AirConditioner>();
tv = make_shared<Television>();
}
void on(){
for(auto light : lights){
light->on();
}
fan->on();
ac->on();
tv->on();
}
void off(){
for(auto light : lights){
light->off();
}
fan->off();
ac->off();
tv->off();
}
private:
vector<shared_ptr<Light> > lights;
shared_ptr<Fan> fan;
shared_ptr<AirConditioner> ac;
shared_ptr<Television> tv;
};
客户端测试 :
//客户端测试
int main(void){
shared_ptr<GeneralSwitchFacade> gsf = make_shared<GeneralSwitchFacade>();
gsf->on();
cout << "-----------" << endl;
gsf->off();
return 0;
}
输出结果:
(End)