Implementing Factory Pattern in C

Chuan Zhang
2 min readAug 13, 2020

Dec. 30. 2015

Factory method is a very important design pattern in object oriented designs[1]. The main goal of this pattern is to allow the client to create objects without having to specify the details of the objects to create. It returns one of several possible classes that share a common super class. This post is not going to discuss factory pattern in C++ or any other OOP language. Instead, a similar implementation of the pattern in the programming language C will be discussed.

Function Factory: prototype

Function factory has two slightly different prototypes:

return_type (*function_factory_name(fac_type1 fac_param1, fac_type2 fac_param2, …))(fun_type1 fun_param1, fun_type2 fun_param2, …);

and

typedef return_type ffac_type_name(fun_type1 fun_param1, fun_type2 fun_param2, …);ffac_type_name *function_factory_name(fac_type1 fac_param1, fac_type2 fac_param2, …);

Function Factory: A Demonstrative Example

Next, I am going to demonstrate function factory in a simple example.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* test0(char* name)
{
char *str;
str = (char*) malloc(strlen(name)*sizeof(char));
strcat(str, “Hello “);
strcat(str, name);
return str;
}
char* test1(char* name)
{
char *str;
str = (char*) malloc(strlen(name)*sizeof(char));
strcat(str, “Welcome “);
strcat(str, name);
return str;
}
char* test2(char* name)
{
char *str;
str = (char*) malloc(strlen(name)*sizeof(char));
strcat(str, “Bye “);
strcat(str, name);
return str;
}
/*************************************
* Function Factory: *
*************************************/
char* (*func(int n))(char* name)
{
switch(n)
{
case 0 : return &test0; break;
case 1 : return &test1; break;
case 2 : return &test2; break;
}
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
fprintf(stderr, “Usage: %s <name>\n”, argv[0]);
exit(1);
}
char str[1024];
int i = 1;
for (; i < argc; i++)
{
strcat(str, argv[i]);
strcat(str, “ “);
}
char* (*test)(char *name);
for (i = 0; i < 3; i++)
{
test = func(i);
printf(“%s\n”, test(str));
}
return 0;
}

As what we have pointed out above, the function factory in the above program can also be declared as follows

/*************************************
* Function Factory: *
*************************************/
typedef char* funcFac(char*);
funcFac *func(int n)
{
… …
}

Below is the output of the above program

~$./funcFactoryExample.out Steve Johnson
Hello Steve Johnson
Welcome Steve Johnson
Bye Steve Johnson

References

--

--