#include <stdio.h>
#include <stdlib.h>
typedef struct _shoes
{
int type;
void (*produce_shoes)(struct _shoes *);
}myShoes;
void produce_leather_shoes(myShoes *pshoes)
{
if (NULL != pshoes)
{
printf("produce the leather shoes!\n");
}
}
void produce_travel_shoes(myShoes *pshoes)
{
if (NULL != pshoes)
{
printf("produce the travel shoes!\n");
}
}
#define LEATHER_TYPE 0x1
#define TRAVEL_TYPE 0x2
myShoes *produce_new_shoes(int type)
{
if (type != LEATHER_TYPE && type != TRAVEL_TYPE)
{
return NULL;
}
myShoes *pshoes = (myShoes *)malloc(sizeof(myShoes));
if (NULL == pshoes)
{
return NULL;
}
pshoes->type = type;
if (LEATHER_TYPE == type)
{
pshoes->produce_shoes = produce_leather_shoes;
}
else
{
pshoes->produce_shoes = produce_travel_shoes;
}
return pshoes;
}
int main()
{
myShoes *pshoes = produce_new_shoes(LEATHER_TYPE);
if (pshoes)
{
pshoes->produce_shoes(pshoes);
free(pshoes);
}
return 0;
}
C语言实现工厂模式
最新推荐文章于 2025-10-20 14:53:45 发布
这篇博客展示了如何在C++中运用结构体和函数指针实现一个简单的工厂模式,用于创建不同类型的鞋子,包括皮革鞋和旅行鞋。通过定义`myShoes`结构体并设置`produce_shoes`成员函数指针,根据传入的类型动态分配内存并初始化鞋子对象。在`main`函数中,创建了一个皮革鞋对象并调用了对应的生产方法。

969

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



