C++实现简单工厂模式
时间: 2023-10-20 10:11:26 浏览: 64
简单工厂模式是一种创建型设计模式,它提供了一个创建对象的统一接口,但由工厂类来决定创建哪种具体类的实例。以下是 C 语言实现简单工厂模式的示例代码:
首先,定义一个抽象的产品类,它包含一个抽象方法:
```
typedef struct {
void (*operation)(void);
} Product;
void product_operation(Product *product) {
product->operation();
}
```
然后,定义两个具体的产品类,它们实现了抽象产品类中的抽象方法:
```
typedef struct {
Product product;
} ConcreteProductA;
static void concrete_product_a_operation(void) {
printf("Concrete Product A Operation\n");
}
ConcreteProductA *create_concrete_product_a(void) {
ConcreteProductA *product = (ConcreteProductA *) malloc(sizeof(ConcreteProductA));
product->product.operation = concrete_product_a_operation;
return product;
}
typedef struct {
Product product;
} ConcreteProductB;
static void concrete_product_b_operation(void) {
printf("Concrete Product B Operation\n");
}
ConcreteProductB *create_concrete_product_b(void) {
ConcreteProductB *product = (ConcreteProductB *) malloc(sizeof(ConcreteProductB));
product->product.operation = concrete_product_b_operation;
return product;
}
```
接着,定义一个简单工厂类,它根据客户端的需求,创建具体的产品实例:
```
typedef enum {
ProductTypeA,
ProductTypeB
} ProductType;
Product *create_product(ProductType type) {
switch (type) {
case ProductTypeA:
return (Product *) create_concrete_product_a();
case ProductTypeB:
return (Product *) create_concrete_product_b();
default:
return NULL;
}
}
```
最后,在客户端代码中调用简单工厂类的创建方法,创建具体的产品实例并调用其方法:
```
int main() {
Product *product = create_product(ProductTypeA);
product_operation(product);
product = create_product(ProductTypeB);
product_operation(product);
return 0;
}
```
输出结果为:
```
Concrete Product A Operation
Concrete Product B Operation
```
阅读全文