设计模式之工厂模式

113 阅读1分钟

介绍:

​ 工厂模式是一种创建型设计模式,同时也是一种比较典型的解耦模式,工厂模式的实质其实就是" 定义一个生产的接口,让客户来决定具体生产什么产品 "。


作用:

  • 能够有效的封装代码,隐蔽具体的生产逻辑:将产品的具体生产过程封装起来,使得调用者根本无需关心产品的具体生产过程,只需告诉工厂自己需要什么样的产品就可以。即便生产过程有所调整,也是对调用者没有任何影响的;
  • 扩展性强:当我们新增另外种类的产品时,对其他类型的产品没有任何影响;

类比:

​ 一个衣服工厂可以根据不同的诉求生产出不同面料的衣服,客户只需要告诉工厂要生产什么面料的衣服就可以,具体生产过程是工厂自己的事情;


代码示例:


typedef enum
{
    COTTON,
    LEATHER,
    FABRIC_MAX,
};

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


void cotton_clothes(void)
{
    printf("Make cotton clothes\r\n");
}
 
void 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->make_clothing = cotton_clothes;
        break;
            
        case LEATHER:
            pClothing->make_clothing = leather_clothes;
        break;
    }
    return pClothing;
}