一、源代码:
#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();
}
二、运行结果: