Factory pattern implementation using ANSI C

Can someone tell me how to implement a factory pattern using ANSI C? If more templates are covered, it will be just a bonus. Doing this in C ++ is trivial for me, but since C has no classes and polymorphism, I'm not quite sure how to do this. I was thinking of creating a “base” structure with all the common data types, and then using void pointers and defining all the common parts of the structures in the same order as in the base structure at the top? Or is it not guaranteed that they end equally in memory?

+3
source share
4 answers

C have pointers to functions and structures. That way you can implement classes in C.

something like this should give you a clue.

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

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

polyclass make_class1() { polyclass result; result.foo = class1_foo; return result; }
+1
source

A factory pattern can also be implemented in C, suppose the following operations are defined by your interface:

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;

So, in order to be able to get an instance of implementations that implements such an interface, you must define a structure with both data and operations, then you can define a creation that will return this structure and, possibly, destruction operations:

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;

You should also define a function that provides you with factory methods, perhaps you should have a way to get the right implementation based on your needs (maybe not a simple parameter, as in the example below):

typedef enum IMPL_TYPE
{
    IMPL_TYPE_1,
    IMPL_TYPE_2
} IMPL_TYPE;
factory_ops* get_factory(int impl_type);

Therefore, it will be used as:

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;
}
+6

The Factory pattern is an object-oriented design pattern.

C is not an object oriented language.

So I would question what is your goal for Factory in C.

0
source

Here at the bottom of the page is a series of articles on templates in C

0
source

Source: https://habr.com/ru/post/1753723/


All Articles