使用ANSI C的工厂模式实现

inq*_*uam 3 c design-patterns factory c89

任何人都可以指点我如何使用ANSI C实现工厂模式?如果覆盖更多的模式,那将只是一个奖励.在C++中这样做对我来说是微不足道的,但由于C没有类和多态,我不太清楚如何做到这一点.我正在考虑使用所有常见数据类型的"基础"结构,然后使用void指针,并按照与顶部基础结构相同的顺序定义结构的所有公共部分?或者不能保证它们在内存中以相同的方式结束?

小智 6

工厂模式也可以在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;
Run Code Online (Sandbox Code Playgroud)

因此,为了能够获得实现此类接口的实现实例,您应该定义一个包含数据和操作的结构,然后您可以定义将返回给您的结构的create操作,也可能是一个destroy操作:

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;
Run Code Online (Sandbox Code Playgroud)

您还应该定义一个为您提供工厂方法的函数,也许您应该有一种方法可以根据您的需要获得正确的实现(可能不是像下面示例中的简单参数):

typedef enum IMPL_TYPE
{
    IMPL_TYPE_1,
    IMPL_TYPE_2
} IMPL_TYPE;
factory_ops* get_factory(int impl_type);
Run Code Online (Sandbox Code Playgroud)

所以它将被用作:

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;
}
Run Code Online (Sandbox Code Playgroud)


yat*_*asu 1

C 有函数指针和结构体。所以你可以用C实现类。

像这样的事情应该给你一个线索。

void class1_foo() {}
void class2_foo() {}

struct polyclass
{
    void (*foo)();
};

polyclass make_class1() { polyclass result; result.foo = class1_foo; return result; }
Run Code Online (Sandbox Code Playgroud)