- 序言
- 环境
- 理解
- 源码
这是一个简单理解的工厂模式,并未涉及复杂的构成方式。
本章节参考自菜鸟教程-工厂模式,理论方面点进去查看理解即可。
其实菜鸟教程已经写得很清楚了,但是我其实并不大想在JAVA下去理解和使用,所以我就在QtC++里再实现一次,当练手也当记录
.
Qt5.12 C++
.
该图并不遵守UML规范,只是单纯为了便于源码快速回忆及理解
.
源码Fectory.h
#includeclass Shape { public: virtual ~Shape(); virtual void draw(); enum ShapeEnum { Rectangle, Square, Circle }; }; class Rectangle : public Shape { public: void draw() override; }; class Square : public Shape { public: void draw() override; }; class Circle : public Shape { public: void draw() override; }; class ShapeFectory { public: static Shape *getShape(int shapeType ); };
.
Fectory.cpp
#include "fectory.h"
Shape::~Shape()
{
}
void Shape::draw()
{
qDebug()<<"Shape";
}
void Rectangle::draw()
{
qDebug()<<"Rectangle";
}
void Square::draw()
{
qDebug()<<"Square";
}
void Circle::draw()
{
qDebug()<<"Circle";
}
Shape *ShapeFectory::getShape(int shapeType)
{
switch ( shapeType ) {
case Shape::Rectangle:
return new Rectangle();
case Shape::Square:
return new Square();
case Shape::Circle:
return new Circle();
default:
return nullptr;
}
}
.
使用的地方
//使用智能指针指向返回的内存,该指针释放时一并释放。 QScopedPointer< Shape > shape( ShapeFectory::getShape( Shape::Rectangle ) ); shape->draw();
输出:
Rectangle
.
注:本人未看过C++版的设计模式,主要是别人不肯发给我,我又没找到资源



