Adios’ Notes

Adios’ Notes

Adios Tsai  //  

Nov 3 / 10:50am

Strategy pattern - Wikipedia, the free encyclopedia

C

A struct in C can be used to define a class, and the strategy can be set using a function pointer. The following mirrors the Python example, and uses C99 features:

#include <stdio.h>
 
void print_sum(int n, int *array) {
  int total = 0;
  for (int i=0; i<n; i++) total += array[i];
  printf("%d", total);
}
 
void print_array(int n, int *array) {
  for (int i=0; i<n; i++) printf("%d ", array[i]);
}
 
int main(void) {
  typedef struct {
    void (*submit_func)(int n, int *array);
    char *label;
  } Button;
 
  // Create two instances with different strategies
  Button button1 = {print_sum, "Add 'em"};
  Button button2 = {print_array, "List 'em"};
 
  int n = 10, numbers[n];
  for (int i=0; i<n; i++) numbers[i] = i;
 
  button1.submit_func(n, numbers);
  button2.submit_func(n, numbers);
 
  return 0;
}

Loading mentions Retweet

0 comments

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    twitter