#include <iostream>
class Shape
{
public:
virtual void drawshape() = 0;
};
class DrawCircle : public Shape
{
public:
void drawshape() {
std::cout << "Circle\n";
}
};
class DrawRect : public Shape
{
public:
void drawshape() {
std::cout << "Rect\n";
}
};
class DrawShape
{
public:
Shape* getshape(std::string shape) {
if ("Circle" == shape) {
return new DrawCircle();
}
if ("Rect" == shape) {
return new DrawCircle();
}
return NULL;
}
};
int main()
{
DrawShape shape;
Shape* p_shape = shape.getshape("Circle");
if (!p_shape) {
std::cout << "Get shape failed.\n";
return -1;
}
p_shape->drawshape();
return 0;
}
C++ 实现设计模式 -- 工厂模式
最新推荐文章于 2022-07-29 21:28:07 发布
本文介绍了一个使用C++实现的图形绘制系统,通过抽象工厂模式创建不同的形状实例,如圆形和矩形。系统定义了一个Shape基类,包含纯虚函数drawshape(),以及从该基类派生的DrawCircle和DrawRect类,分别用于绘制圆形和矩形。DrawShape类作为工厂类,根据输入字符串创建相应的形状实例。
1594

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



