- 实现基类 Shape
- 实现 Shape 基类子类 两个
- 实现创建子类对象的工厂类
#include <iostream>
#include <map>
using namespace std;
class Shape
{
public:
Shape()
{
cout << "Shape" << endl;
}
virtual ~Shape()
{
cout << "~Shape" << endl;
}
virtual void draw() = 0;
virtual void erase() = 0;
};
class Circle :public Shape
{
public:
Circle()
{
cout << "Circle" << endl;
}
virtual ~Circle()
{
cout << "~Circle" << endl;
}
void draw()
{
cout << "circle::drap" << endl;
}
void erase()
{
cout << "circle::erase" << endl;
}
};
class Square :public Shape
{
public:
Square()
{
cout << "Square" << endl;
}
virtual ~Square()
{
cout << "~Square" << endl;
}
void draw()
{
cout << "square::drap" << endl;
}
void erase()
{
cout << "square::erase" << endl;
}
};
class ShapeFactory
{
public:
ShapeFactory()
{
cout << "ShapeFactory" << endl;
}
virtual ~ShapeFactory()
{
cout << "~ShapeFactory" << endl;
}
static Shape* createShape(int type)
{
if (type == 0)
{
return new Square();
}
else {
return new Circle();
}
}
};
int main()
{
Shape* shape = ShapeFactory::createShape(0);
shape->draw();
shape->erase();
shape = ShapeFactory::createShape(1);
shape->draw();
shape->erase();
return 0;
}