Strategy via Function Pointers
The strategy pattern in C is a struct of function pointers (or one function pointer) that you swap to change an algorithm without changing the caller. Sort, compress, and log are the usual examples.
Detailed Explanation
A qsort comparator is a one-function strategy. A larger strategy is a table:
struct Compressor {
int (*encode)(const unsigned char *in, size_t n,
unsigned char *out, size_t *out_n);
int (*decode)(const unsigned char *in, size_t n,
unsigned char *out, size_t *out_n);
};
The rest of the program holds struct Compressor c and calls c.encode(...). At startup you install the gzip table or the no-op table. The call sites do not #ifdef. Tests install a fake that records arguments.
This is the same machine as a vtable, without the claim that the object is a subtype. The strategy object may have no state, or it may carry a void *ctx. When it has state, you have an interface struct.
Compared with a switch (kind), a strategy lets you add a new kind in another file without editing the switch. Compared with #ifdef, it lets you choose at run time. The cost is an indirect call, which is noise except in a tiny hot loop.
Do not put twelve strategies in one object if only one changes. Keep the table small. Keep the functions' types identical; a cast to silence a mismatch is undefined behavior waiting for a new argument.
Code Examples
#include <stdio.h>
struct Greeter {
void (*hello)(const char *name);
};
static void hello_plain(const char *name)
{
printf("hello %s\n", name);
}
static void hello_loud(const char *name)
{
printf("HELLO %s\n", name);
}
int main(void)
{
struct Greeter g = { hello_plain };
g.hello("c"); /* prints: hello c */
g.hello = hello_loud;
g.hello("c"); /* prints: HELLO c */
return 0;
}Common Gotchas
A strategy with hidden global state is not reentrant
pass a `ctx`.
`qsort`'s comparator is a strategy
the library did not hard-code `<` on `int`.
Installing a function with the wrong prototype via a cast is undefined behavior
Installing a function with the wrong prototype via a cast is undefined behavior
Swapping the strategy while another thread is in a call needs a lock or a stop-t
Swapping the strategy while another thread is in a call needs a lock or a stop-the-world