Builder pattern in C
From the wikipedia page:
... the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.
So, one way to achieve this would be to define a builder object with an interface that allows you to describe the object you want to build. Then you provide another method that allows you to construct the target object based on that description.
Using the car example in the wikipedia page:
struct car;
struct car_builder;
enum CAR_OPTIONS { CAR_OPTION_NOT_AN_OPTION,
CAR_OPTION_SEATS, CAR_OPTION_NAVIGATION, /* ... */ };
struct car_builder * create_car_builder ();
/*
* Positive option sets the option, negative option unsets it.
* If the option takes a parameter, pass them in the varargs.
*/
void car_builder_option (struct car_builder *, int option, ...);
/*
* builds a car
*/
const struct car * car_builder_construct (struct car_builder *options);
/*
* junks the car
*/
void car_builder_destruct (const struct car *);
/* ... */
struct car_builder *options = create_car_builder();
car_builder_option(options, CAR_OPTION_SEATS, 2);
car_builder_option(options, CAR_OPTION_SPORT_CAR);
car_builder_option(options, CAR_OPTION_NAVIGATION);
car_builder_option(options, -CAR_OPTION_POWER_WINDOWS);
const struct car *car = car_builder_construct(options);
Returning a pointer to a const struct car
signals to the caller that the returned object cannot be modified directly.