外观模式

随声附和 提交于 2020-03-03 07:03:15

外观模式

作用:隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。属于结构型模式。这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。提高子系统的独立性和可移植性.简化了类之间的依赖关系

使用场景:

  • 当你要为一个复杂子系统提供一个简单接口时
  • 客户程序与抽象类的实现部分之间存在着很大的依赖性
  • 当你需要构建一个层次结构的子系统时

代码示例

#include<iostream>
 
using namespace std;
 
//创建一个形状的抽象接口shape
class shape
{
public:
	shape() {};
	virtual ~shape() {};
	virtual void draw()=0;
};
 
 
//创建实现形状抽象接口的实体类rectangle
class rectangle :public shape
{
public:
	rectangle() {};
	~rectangle() {};
	void draw();
};
 
void rectangle::draw()
{
	cout << "rectangle::draw()" << endl;
}
 
//创建实现形状抽象接口的实体类square
class square :public shape
{
public:
	square() {};
	~square() {};
	void draw();
};
 
void square::draw()
{
	cout << "square::draw()" << endl;
}
 
//创建实现形状抽象接口的实体类circle
class circle :public shape
{
public:
	circle() {};
	~circle() {};
	void draw();
};
 
void circle::draw()
{
	cout << "circle::draw()" << endl;
}
 
//创建一个外观类。隐藏系统的复杂性,提供访问系统的接口
class shapemaker
{
public:
	shapemaker();
	~shapemaker();
	void drawcircle();
	void drawrectangle();
	void drawsquare();
private:
	shape *circlet;
	shape *rectanglet;
	shape *squaret;
};
 
shapemaker::shapemaker()
{
	circlet = (shape*)new circle();
	rectanglet = (shape*)new rectangle();
	squaret = (shape*)new square();
}
shapemaker::~shapemaker()
{
	delete circlet;
	circlet = NULL;
 
	delete rectanglet;
	rectanglet = NULL;
 
	delete squaret;
	squaret = NULL;
}
void shapemaker::drawcircle()
{
	circlet->draw();
}
void shapemaker::drawrectangle()
{
	rectanglet->draw();
}
void shapemaker::drawsquare()
{
	squaret->draw();
}
 
 
int main()
{
	shapemaker *shapemakert = new shapemaker();
	shapemakert->drawcircle();
	shapemakert->drawrectangle();
	shapemakert->drawsquare();
	delete shapemakert;
	shapemakert = NULL;
	system("pause");
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!