خرید بک لینک

Vote count: 0

I are taking a low level course in embedded systems and have been assigned the task of replicating some design pattes in C. I have gotten observer and delegator working I am really struggling with the decorator patte. I do realize that many people think that design pattes 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 retuing the cost to make it easy) but for the life of me caot get it to work: http://www.newthinktank.com/2012/09/decorator-design-patte-tutorial/

This is the UML for the example (as I said I am only doing the getCost part):

Decorator Patte for Pizza example

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 () {
    retu 5;
}
double thickCrustPizzaCost () {
    retu 7;
}

// these are the toppings
double mozzarellaCost (toppingDecorator_t * self) {
    retu self->tempPizza.getCost () + 3.0;
}
double tomatoCost (toppingDecorator_t * self) {
    retu 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 %fn", plainPizza.getCost ());
    printf ("A mozzarella pizza costs %fn", mozzarella.getCost (&mozzarella));
    printf ("A tomato and mozzarella pizza costs %fn", tomato.getCost (&mozzarella));
}

asked 25 secs ago

برچسب: نویسنده: استخدام کار تاريخ: سه شنبه 25 اسفند 1394 ساعت: 2:13

صفحه بندی