工厂方法模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。工厂方法模式将对象的创建与使用分离,客户端无需关心对象的创建细节,只需通过工厂接口请求所需的对象。
在工厂方法模式中,我们定义一个用于创建对象的接口(抽象工厂),然后让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
由于C语言不支持面向对象编程中的接口和继承等特性,我们将通过函数指针的方式模拟工厂方法模式。下面是一个简单的C语言示例:
这个是个见简单工厂模式, 抽象工厂模式其实也差不多
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 图形接口
typedef struct {
void (*draw)();
} Shape;
// 圆形
typedef struct {
Shape shape;
} Circle;
void Circle_draw() {
printf("绘制圆形\n");
}
Circle createCircle() {
Circle circle;
circle.shape.draw = Circle_draw;
return circle;
}
// 矩形
typedef struct {
Shape shape;
} Rectangle;
void Rectangle_draw() {
printf("绘制矩形\n");
}
Rectangle createRectangle() {
Rectangle rectangle;
rectangle.shape.draw = Rectangle_draw;
return rectangle;
}
// 工厂函数
Shape createShape(char* type) {
if (strcmp(type, "Circle") == 0) {
Circle circle = createCircle();
return circle.shape;
} else if (strcmp(type, "Rectangle") == 0) {
Rectangle rectangle = createRectangle();
return rectangle.shape;
} else {
printf("未知的类型\n");
exit(1);
}
}
int main() {
Shape shape1 = createShape("Circle");
shape1.draw();
Shape shape2 = createShape("Rectangle");
shape2.draw();
return 0;
}