title: C decorator design pattern (using the pizza example)
body: <p>I are taking a low level course in embedded systems and have been assigned the task of replicating some design patterns in C. I have gotten observer and delegator working I am really struggling with the decorator pattern. I do realize that many people think that design patterns do not belong in a "low-level" language like C but I do not have an option - it needs to be done to pass this course. All the examples I have found are for OO programming languages. I'm using this Java pizza example as a basis (just returning the cost to make it easy) but for the life of me cannot get it to work: <a href="http://www.newthinktank.com/2012/09/decorator-design-pattern-tutorial/" rel="nofollow noreferrer">http://www.newthinktank.com/2012/09/decorator-design-pattern-tutorial/</a></p>
  
  <p>This is the UML for the example (as I said I am only doing the getCost part): </p>
  
  <p><a href="https://i.stack.imgur.com/tMyWd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tMyWd.jpg" alt="Decorator Pattern for Pizza example"></a></p>
  
  <p>I have spent about 2 days trying to get this to work but am just stuck. I have added the code that I have but am stumped how to add the tomato to the pizza so that the cost is added up correctly</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  typedef struct _pizza {
      double (* getCost) ();
  } pizza_t;
  
  typedef struct _toppingDecorator {
      double (* getCost) ();
      pizza_t tempPizza;
  } toppingDecorator_t;
  
  // these are the pizzas
  double plainPizzaCost () {
      return 5;
  }
  double thickCrustPizzaCost () {
      return 7;
  }
  
  // these are the toppings
  double mozzarellaCost (toppingDecorator_t * self) {
      return self-&gt;tempPizza.getCost () + 3.0;
  }
  double tomatoCost (toppingDecorator_t * self) {
      return self-&gt;tempPizza.getCost () + 1;
  }
  
  int main(int argc, const char * argv[]) {
  
      pizza_t plainPizza;
      plainPizza.getCost = &amp;plainPizzaCost;
  
      pizza_t thickCrustPizza;
      thickCrustPizza.getCost = &amp;thickCrustPizzaCost;
  
      toppingDecorator_t mozzarella;
      mozzarella.tempPizza = plainPizza;
      mozzarella.getCost = &amp;mozzarellaCost;
  
      toppingDecorator_t tomato;
      tomato.tempPizza = mozzarella.tempPizza;
      tomato.getCost = &amp;tomatoCost;
  
      // now print the cost
      printf ("A plain pizza costs %f\n", plainPizza.getCost ());
      printf ("A mozzarella pizza costs %f\n", mozzarella.getCost (&amp;mozzarella));
      printf ("A tomato and mozzarella pizza costs %f\n", tomato.getCost (&amp;mozzarella));
  }
  </code></pre>