设计模式之外观模式实例(c++)

外观模式:

外观模式为子系统中的一组接口提供一个统一的入口。其定义了一个高层的接口,这个接口使得这一子系统更加容易使用。

在外观模式中,外部与一个或者多个子系统的通信,可以通过一个统一的外观对象来进行。

外观模式实例之电源总开关:

设计模式之外观模式实例(c++)_第1张图片

从类图我们可以看出,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("左前"));
		lights.push_back(make_shared("右前"));
		lights.push_back(make_shared("左后"));
		lights.push_back(make_shared("右后"));
		fan = make_shared();
		ac = make_shared();
		tv = make_shared();
	}
	
	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 > lights;
	shared_ptr fan;
	shared_ptr ac;
	shared_ptr tv;
}; 

 客户端测试 :

//客户端测试 
int main(void){
	shared_ptr gsf = make_shared();
	gsf->on();
	cout << "-----------" << endl;
	gsf->off();
	return 0;
}

输出结果:

 设计模式之外观模式实例(c++)_第2张图片

(End)

 

 

你可能感兴趣的:(设计模式(c++),设计模式,装饰器模式,c++)