一、源代码:
#include<iostream>
#include<memory>
#include<map>
#include<array>
using namespace std;
class Shape
{
public:
virtual void draw() = 0;
virtual ~Shape() = default;
};
class Circle:public Shape
{
public:
Circle(string color)
{
this->_color = color;
}
void setX(int x)
{
this->_x = x;
}
void setY(int y)
{
this->_y = y;
}
void setRadius(int radius)
{
this->_radius = radius;
}
virtual void draw() override
{
cout<<" Circle:Draw()->[Color: "<<_color<<",x: "<<_x<<",y: "<<_y<<",radius: "<<_radius<<"]"<<endl;
}
private:
string _color;
int _x;
int _y;
int _radius;
};
class ShapeFactory
{
public:
static shared_ptr<Shape> getCircle(string color)
{
shared_ptr<Shape> circle = circleMap[color];
if(circle == nullptr)
{
circle = make_shared<Circle>(color);
circleMap[color] = circle;
cout<<"Creating circle of color: "<<color<<endl;
}
return circle;
}
private:
static map<string,shared_ptr<Shape>> circleMap;
};
map<string,shared_ptr<Shape>> ShapeFactory::circleMap = {};
int main()
{
array<string,5> colors = {"Red","Green","Blue","White","Black"};
for(int i = 0;i< 20;++i)
{
shared_ptr<Circle> circle = dynamic_pointer_cast<Circle>(ShapeFactory::getCircle(colors[rand()%5]));
circle->setX(rand()%100);
circle->setY(rand()%100);
circle->setRadius(rand()%50+1);
circle->draw();
}
return 0;
}
二、运行结果: