外观模式
外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式。这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。
使用场景
为复杂的模块或子系统提供外界访问的模块。
子系统相互独立。
在层析结构中,可以使用外观模式定义系统的每一层的入口。
优缺点
优点:
1、减少系统相互依赖。
2、提高灵活性。
3、提高了安全性。
缺点:
不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。
注意事项
在层次化结构中,可以使用外观模式定义系统中每一层的入口。
UML结构图
代码实现
interface.h
创建抽象类 - 图形; 创建具体类 - 圆形、正方形、矩形
#include <iostream>
using namespace std;
class Shape //基类-图形
{
public:
Shape() {}
virtual ~Shape() {}
virtual void draw() = 0;
};
class Square: public Shape //子类-圆形
{
public:
void draw() { cout << "draw Square" << endl; }
};
class Circle: public Shape //子类-正方形
{
public:
void draw() { cout << "draw Circle" << endl; }
};
class Rectangle: public Shape //子类-矩形
{
public:
void draw() { cout << "draw Rectangle" << endl; }
};
shapemaker.h
创建外观类,提供接口给客户使用
#include "interface.h"
class ShapeMaker
{
public:
ShapeMaker()
{
this->circle = new Circle();
this->square = new Square();
this->rectangle = new Rectangle();
}
void drawCircle() { circle->draw(); }
void drawSquare() { square->draw(); }
void drawRectangle() { rectangle->draw(); }
private:
Shape *circle;
Shape *square;
Shape *rectangle;
};
main.cpp
实例应用 - 使用外观类画出不同的图形
#include "shapemaker.h"
int main()
{
ShapeMaker shapeMaker;
shapeMaker.drawCircle();
shapeMaker.drawSquare();
shapeMaker.drawRectangle();
return 0;
}
运行结果:
draw Circle
draw Square
draw Rectangle
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓