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

被折叠的 条评论
为什么被折叠?



