2.创建型模式--工厂模式

工厂方法模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。工厂方法模式将对象的创建与使用分离,客户端无需关心对象的创建细节,只需通过工厂接口请求所需的对象。

在工厂方法模式中,我们定义一个用于创建对象的接口(抽象工厂),然后让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

由于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;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

入门->放弃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值