工厂方法模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。工厂方法模式将对象的创建与使用分离,客户端无需关心对象的创建细节,只需通过工厂接口请求所需的对象。
在工厂方法模式中,我们定义一个用于创建对象的接口(抽象工厂),然后让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
由于C语言不支持面向对象编程中的接口和继承等特性,我们将通过函数指针的方式模拟工厂方法模式。下面是一个简单的C语言示例:
#include <stdio.h>
#include <stdlib.h>
// 定义产品接口
typedef struct Product {
void (*operation)(); // 操作函数指针
} Product;
// 具体产品A
typedef struct ProductA {
Product product;
} ProductA;
void ProductA_operation() {
printf("ProductA operation\n");
}
// 具体产品B
typedef struct ProductB {
Product product;
} ProductB;
void ProductB_operation() {
printf("ProductB operation\n");
}
// 创建产品A的工厂方法
ProductA* createProductA() {
ProductA* productA = (ProductA*)malloc(sizeof(ProductA));
productA->product.operation = ProductA_operation;
return productA;
}
// 创建产品B的工厂方法
ProductB* createProductB() {
ProductB* productB = (ProductB*)malloc(sizeof(ProductB));
productB->product.operation = ProductB_operation;
return productB;
}
// 工厂接口(函数指针)
typedef Product* (*FactoryMethod)();
// 客户端代码
void clientCode(FactoryMethod factory) {
Product* product = factory();
if (product != NULL) {
product->operation(); // 使用产品
free(product); // 释放产品内存
}
}
int main() {
printf("Creating and using ProductA:\n");
clientCode(createProductA); // 传递创建产品A的工厂方法
printf("Creating and using ProductB:\n");
clientCode(createProductB); // 传递创建产品B的工厂方法
return 0;
}