外观模式
作用:隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。属于结构型模式。这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。提高子系统的独立性和可移植性.简化了类之间的依赖关系
使用场景:
- 当你要为一个复杂子系统提供一个简单接口时
- 客户程序与抽象类的实现部分之间存在着很大的依赖性
- 当你需要构建一个层次结构的子系统时
代码示例
#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;
}
来源:CSDN
作者:WideHunt
链接:https://blog.csdn.net/WideHunt/article/details/104618101