当前位置: 首页 > news >正文

C语言- 工厂模式详解与实践

文章目录

  • C语言工厂模式详解与实践
    • 1. 什么是工厂模式?
    • 2. 为什么需要工厂模式?
    • 3. 实际应用场景
    • 4. 代码实现
      • 4.1 UML 关系图
      • 4.2 头文件 (device_factory.h)
      • 4.3 实现文件 (device_factory.c)
      • 4.4 使用示例 (main.c)
    • 5. 代码分析
      • 5.1 关键设计点
      • 5.2 实现特点
    • 6. 编译和运行
    • 7. 注意事项
    • 8. 改进建议
    • 9. 总结
    • 参考资料

C语言工厂模式详解与实践

1. 什么是工厂模式?

工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,而是通过一个共同的接口来指向新创建的对象。

2. 为什么需要工厂模式?

  • 封装对象创建过程
  • 解耦对象的创建和使用
  • 集中管理对象创建
  • 方便扩展新类型
  • 统一的创建接口

3. 实际应用场景

  • 设备驱动创建
  • 数据库连接管理
  • 通信协议处理器
  • 图形界面元素创建
  • 日志记录器实现

4. 代码实现

4.1 UML 关系图

DeviceFactory
+createDevice()
Device
+init()
+operate()
+destroy()
SerialDevice
+init()
+operate()
+destroy()
NetworkDevice
+init()
+operate()
+destroy()

4.2 头文件 (device_factory.h)

#ifndef DEVICE_FACTORY_H
#define DEVICE_FACTORY_H

#include <stdbool.h>

// 设备类型
typedef enum {
    DEVICE_SERIAL,
    DEVICE_NETWORK,
    DEVICE_USB,
    DEVICE_MAX
} DeviceType;

// 设备操作结构体
typedef struct {
    bool (*init)(void* config);
    bool (*operate)(void* data, int size);
    void (*destroy)(void);
    const char* name;
} Device;

// 设备配置
typedef struct {
    char port[32];    // 端口号或地址
    int baudrate;     // 波特率或其他参数
    void* extra;      // 额外参数
} DeviceConfig;

// 创建设备
Device* create_device(DeviceType type, DeviceConfig* config);

// 销毁设备
void destroy_device(Device* device);

#endif // DEVICE_FACTORY_H

4.3 实现文件 (device_factory.c)

#include "device_factory.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 串口设备实现
static bool serial_init(void* config) {
    DeviceConfig* cfg = (DeviceConfig*)config;
    printf("初始化串口设备: %s, 波特率: %d\n", cfg->port, cfg->baudrate);
    return true;
}

static bool serial_operate(void* data, int size) {
    printf("串口设备操作: 数据大小 %d\n", size);
    return true;
}

static void serial_destroy(void) {
    printf("销毁串口设备\n");
}

// 网络设备实现
static bool network_init(void* config) {
    DeviceConfig* cfg = (DeviceConfig*)config;
    printf("初始化网络设备: %s\n", cfg->port);
    return true;
}

static bool network_operate(void* data, int size) {
    printf("网络设备操作: 数据大小 %d\n", size);
    return true;
}

static void network_destroy(void) {
    printf("销毁网络设备\n");
}

// USB设备实现
static bool usb_init(void* config) {
    DeviceConfig* cfg = (DeviceConfig*)config;
    printf("初始化USB设备: %s\n", cfg->port);
    return true;
}

static bool usb_operate(void* data, int size) {
    printf("USB设备操作: 数据大小 %d\n", size);
    return true;
}

static void usb_destroy(void) {
    printf("销毁USB设备\n");
}

// 设备模板表
static const Device device_templates[] = {
    {serial_init, serial_operate, serial_destroy, "串口设备"},
    {network_init, network_operate, network_destroy, "网络设备"},
    {usb_init, usb_operate, usb_destroy, "USB设备"}
};

Device* create_device(DeviceType type, DeviceConfig* config) {
    if (type >= DEVICE_MAX || !config) {
        return NULL;
    }
    
    Device* device = (Device*)malloc(sizeof(Device));
    memcpy(device, &device_templates[type], sizeof(Device));
    
    if (!device->init(config)) {
        free(device);
        return NULL;
    }
    
    return device;
}

void destroy_device(Device* device) {
    if (device) {
        device->destroy();
        free(device);
    }
}

4.4 使用示例 (main.c)

#include "device_factory.h"
#include <stdio.h>

int main() {
    // 创建串口设备
    DeviceConfig serial_config = {
        .port = "COM1",
        .baudrate = 115200
    };
    Device* serial_dev = create_device(DEVICE_SERIAL, &serial_config);
    
    // 创建网络设备
    DeviceConfig network_config = {
        .port = "192.168.1.100",
        .baudrate = 0
    };
    Device* network_dev = create_device(DEVICE_NETWORK, &network_config);
    
    // 创建USB设备
    DeviceConfig usb_config = {
        .port = "USB0",
        .baudrate = 0
    };
    Device* usb_dev = create_device(DEVICE_USB, &usb_config);
    
    // 测试设备操作
    printf("\n=== 测试设备操作 ===\n");
    char test_data[] = "Hello, Device!";
    
    if (serial_dev) {
        printf("\n%s:\n", serial_dev->name);
        serial_dev->operate(test_data, sizeof(test_data));
    }
    
    if (network_dev) {
        printf("\n%s:\n", network_dev->name);
        network_dev->operate(test_data, sizeof(test_data));
    }
    
    if (usb_dev) {
        printf("\n%s:\n", usb_dev->name);
        usb_dev->operate(test_data, sizeof(test_data));
    }
    
    // 销毁设备
    destroy_device(serial_dev);
    destroy_device(network_dev);
    destroy_device(usb_dev);
    
    return 0;
}

5. 代码分析

5.1 关键设计点

  1. 统一的设备接口
  2. 工厂方法封装
  3. 设备模板管理
  4. 配置参数传递

5.2 实现特点

  1. 函数指针实现多态
  2. 模板表简化创建
  3. 错误处理完善
  4. 资源管理安全

6. 编译和运行

gcc -c device_factory.c -o device_factory.o
gcc -c main.c -o main.o
gcc device_factory.o main.o -o factory_demo

7. 注意事项

  1. 设备初始化检查
  2. 内存管理安全
  3. 错误处理完整
  4. 配置参数验证

8. 改进建议

  1. 添加设备状态管理
  2. 实现设备查找功能
  3. 支持动态设备注册
  4. 添加设备池管理

9. 总结

工厂模式通过封装对象的创建过程,提供了一种灵活且可扩展的对象创建机制。这种模式特别适合处理需要创建多种类型对象的场景。

参考资料

  1. 《设计模式:可复用面向对象软件的基础》
  2. 《C语言程序设计》
  3. 《嵌入式系统设计》

相关文章:

  • 常见中间件漏洞攻略-Apache篇
  • datetime“陷阱”与救赎:扒“时间差值”证道
  • Pytorch实现之对称卷积神经网络结构实现超分辨率
  • Pytorch深度学习教程_9_nn模块构建神经网络
  • 数据结构——哈夫曼编码、哈夫曼树
  • SAP-ABAP:SAP BW模块架构与实战应用详解
  • 使用Python将视频转化为gif
  • AF3 Rotation 类解读
  • stc8g1k08a+cd4017红绿灯
  • 嵌入式学习(31)-Lora模块A39C-T400A30D1a
  • 数据结构5(初):续写排序
  • HarmonyOS NEXT(九) :图形渲染体系
  • 嵌入式八股文学习——STL相关内容学习
  • 测试专项4:AI算法测试在测试行业中,该如何定位自己自述
  • 地理编码/经纬度解析/经纬度地址转换接口如何用JAVA对接
  • ui_auto_study(持续更新)
  • 当今前沿科技:改变世界的最新技术趋势
  • 【Spring】深入理解 Spring 事务管理
  • VScode
  • Java 中的多线程:核心概念与应用场景
  • 消息人士称泽连斯基已启程前往土耳其
  • 2025财政观察|长三角“三公”经费普降,钱要用在刀刃上
  • 马上评|让查重回归促进学术规范的本意
  • 广东省人大教科文卫委原主任委员梁万里被开除党籍:退休后受贿仍不知止
  • 中美日内瓦经贸会谈联合声明
  • 2025年上海好护士揭晓,上海护士五年增近两成达12.31万人