一、源代码:
#include<iostream>
#include<memory>
using namespace std;
class Shape
{
public:
virtual void draw() = 0;
virtual ~Shape() = default;
};
class Rectangle:public Shape
{
public:
virtual void draw() override
{
cout<<"Rectangle::draw()"<<endl;
}
};
class Square:public Shape
{
public:
virtual void draw() override
{
cout<<"Square::draw()"<<endl;
}
};
class Circle:public Shape
{
public:
virtual void draw() override
{
cout<<"Circle::draw()"<<endl;
}
};
class ShapeMaker
{
public:
ShapeMaker()
{
this->_circle = make_shared<Circle>();
this->_rectangle = make_shared<Rectangle>();
this->_square = make_shared<Square>();
}
void drawCircle()
{
this->_circle->draw();
}
void drawRectangle()
{
this->_rectangle->draw();
}
void drawSquare()
{
this->_square->draw();
}
private:
shared_ptr<Shape> _circle;
shared_ptr<Shape> _rectangle;
shared_ptr<Shape> _square;
};
int main()
{
shared_ptr<ShapeMaker> shapeMaker = make_shared<ShapeMaker>();
shapeMaker->drawCircle();
shapeMaker->drawRectangle();
shapeMaker->drawSquare();
}
二、运行结果:

本文通过C++实现了一个图形工厂模式的示例,包括圆形、矩形和正方形等基本图形的创建与绘制。使用共享指针进行资源管理,展示了如何在面向对象编程中运用抽象基类和派生类。
844

被折叠的 条评论
为什么被折叠?



