C++工厂方法DEMO
时间: 2023-02-26 15:11:09 浏览: 76
以下是 C 语言中实现工厂方法的示例代码:
```
#include <stdio.h>
typedef enum {
CIRCLE,
SQUARE,
RECTANGLE
} ShapeType;
typedef struct {
int id;
const char* name;
} Shape;
Shape* createCircle(int id) {
Shape* circle = (Shape*)malloc(sizeof(Shape));
circle->id = id;
circle->name = "Circle";
return circle;
}
Shape* createSquare(int id) {
Shape* square = (Shape*)malloc(sizeof(Shape));
square->id = id;
square->name = "Square";
return square;
}
Shape* createRectangle(int id) {
Shape* rectangle = (Shape*)malloc(sizeof(Shape));
rectangle->id = id;
rectangle->name = "Rectangle";
return rectangle;
}
Shape* createShape(ShapeType type, int id) {
switch (type) {
case CIRCLE:
return createCircle(id);
case SQUARE:
return createSquare(id);
case RECTANGLE:
return createRectangle(id);
default:
return NULL;
}
}
int main() {
Shape* shape1 = createShape(CIRCLE, 1);
printf("Shape 1: id = %d, name = %s\n", shape1->id, shape1->name);
Shape* shape2 = createShape(SQUARE, 2);
printf("Shape 2: id = %d, name = %s\n", shape2->id, shape2->name);
Shape* shape3 = createShape(RECTANGLE, 3);
printf("Shape 3: id = %d, name = %s\n", shape3->id, shape3->name);
return 0;
}
```
运行该程序的结果为:
```
Shape 1: id = 1, name = Circle
Shape 2: id = 2, name = Square
Shape 3: id = 3, name = Rectangle
```
该示例使用了工厂方法模式,通过 `createShape` 函数来创建不同类型的图形对象,而不是直接创建图形对象。这使得我们可以在后续的代码中灵活地更改图形的创建方式,而不影响到其他部分的代码。