谁能指出我如何使用 ANSI C 实现工厂模式的参考?如果涵盖更多模式,那将是一个奖励。在 C++ 中做这件事对我来说是微不足道的,但由于 C 没有类和多态性,我不太确定如何去做。我正在考虑拥有一个包含所有常见数据类型的“基本”结构,然后使用 void 指针,并以与顶部基本结构相同的顺序定义结构的所有公共部分?还是不能保证它们在内存中以相同的方式结束?
问问题
8351 次
4 回答
7
工厂模式也可以在 C 中实现,假设以下是您的接口定义的操作:
typedef int (*operations_1) (void *data);
typedef int (*operations_2) (void *data);
typedef struct impl_ops_t
{
operations_1 op1;
operations_2 op2;
} impl_ops_t;
因此,为了能够获得实现此类接口的实现实例,您应该定义一个包含数据和操作的结构,然后您可以定义创建操作,该操作将返回给您该结构,可能还有一个销毁操作:
typedef struct ctx_t
{
void *data;
impl_ops_t *operations;
} ctx_t;
typedef ctx_t (*create_handle) (void);
typedef void (*destroy_handle) (ctx_t **ptr);
typedef struct factory_ops
{
create_handle create;
destroy_handle destroy;
} factory_ops;
您还应该定义一个为您提供工厂方法的函数,也许您应该有一种方法可以根据您的需要获得正确的实现(可能不是下面示例中的简单参数):
typedef enum IMPL_TYPE
{
IMPL_TYPE_1,
IMPL_TYPE_2
} IMPL_TYPE;
factory_ops* get_factory(int impl_type);
所以它会像这样使用:
main (...)
{
factory_ops fact = get_factory(IMPL_TYPE_2);
// First thing will be calling the factory method of the selected implementation
// to get the context structure that carry both data ptr and functions pointer
ctx_t *c = fact->create();
// So now you can call the op1 function
int a = c->operations->op1(c->data);
// Doing something with returned value if you like..
int b = c->operations->op2(c->data);
// Doing something with returned value if you like..
fact->destroy(&c);
return 0;
}
于 2013-03-26T18:38:07.943 回答
1
C有函数指针和结构。所以你可以在 C 中实现类。
这样的事情应该给你一个线索。
void class1_foo() {}
void class2_foo() {}
struct polyclass
{
void (*foo)();
};
polyclass make_class1() { polyclass result; result.foo = class1_foo; return result; }
于 2010-07-08T14:22:50.123 回答
1
这里,在页面的底部,是一系列关于 C 中的模式的文章
于 2010-07-08T14:39:24.067 回答
0
工厂模式是一种面向对象的设计模式。
C 不是面向对象的语言。
因此,我会质疑您对 C 语言工厂的目标是什么。
于 2010-07-08T14:22:31.463 回答