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

介绍:

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


作用:

​ 隐蔽具体的生产逻辑,根据不同的要求生产出不同的产品,就像switch-case一样;


类比:

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


代码示例:

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;
}
上一篇:fabric node.js调用智能合约


下一篇:Fabric镜像