设计模式之工厂模式(C语言)

本文介绍了工厂模式,一种创建型设计模式,用于隐蔽具体的生产逻辑,根据不同需求生成不同类型的产品。以衣服工厂为例,说明如何通过工厂模式根据客户要求生产不同面料的衣服。代码示例展示了如何使用C语言实现工厂模式,通过结构体和函数指针动态创建具备特定生产方法的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍:

工厂模式是一种创建型设计模式;


作用:

​ 隐蔽具体的生产逻辑,根据不同的要求生产出不同的产品;


类比:

​ 一个衣服工厂可以根据不同的诉求生产出不同面料的衣服;


代码示例:

typedef enum
{
    COTTON,
    LEATHER,
    FABRIC_MAX,
}

typedef struct _Clothing
{
    int fabric; /*面料*/
    void (*generate_clothing)(void);
}Clothing;


void make_cotton_clothes(void)
{
    printf("Make cotton clothes\r\n");
}
 
void make_leather_clothes(void)
{
    printf("Make leather clothes\r\n");
}

 
Clothing* manufacture_clothing(int fabric)
{
    assert(fabric < FABRIC_MAX);
 
    Clothing* pClothing = (Clothing*)malloc(sizeof(Clothing));
    assert(NULL != pClothing);
 
    memset(pClothing, 0, sizeof(Clothing));
    
    pClothing->fabric = fabric;
    
    switch(fabric)
    {
        case COTTON:
            pClothing->generate_clothing = make_cotton_clothes;
        break;
            
        case LEATHER:
            pClothing->generate_clothing = make_leather_clothes;
        break;
    }
    return pClothing;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值