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: http://ift.tt/1LmVHtJ
This is the UML for the example (as I said I am only doing the getCost part):
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
#include <stdio.h>
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->tempPizza.getCost () + 3.0;
}
double tomatoCost (toppingDecorator_t * self) {
return self->tempPizza.getCost () + 1;
}
int main(int argc, const char * argv[]) {
pizza_t plainPizza;
plainPizza.getCost = &plainPizzaCost;
pizza_t thickCrustPizza;
thickCrustPizza.getCost = &thickCrustPizzaCost;
toppingDecorator_t mozzarella;
mozzarella.tempPizza = plainPizza;
mozzarella.getCost = &mozzarellaCost;
toppingDecorator_t tomato;
tomato.tempPizza = mozzarella.tempPizza;
tomato.getCost = &tomatoCost;
// now print the cost
printf ("A plain pizza costs %f\n", plainPizza.getCost ());
printf ("A mozzarella pizza costs %f\n", mozzarella.getCost (&mozzarella));
printf ("A tomato and mozzarella pizza costs %f\n", tomato.getCost (&mozzarella));
}
Aucun commentaire:
Enregistrer un commentaire