On Sun, 14 Oct 2007 15:42:25 +0200, Thomas Mlynarczyk
<th****@mlynarczyk-webdesign.dewrote:
>But how to create a pizza with 2 toppings ??
I would do something like this:
interface NotForFree { function getPrice(); }
class Pizza implements NotForFree { ... }
class Margherita extends Pizza { ... }
class Topping implements NotForFree { ... }
class CheeseTopping extends Topping { ... ]
class OnionTopping extends Topping { ... }
$pizza = new Margherita;
$pizza->addTopping( new CheeseTopping );
$pizza->addTopping( new OnionsTopping );
$pizza->getPrice();
/* or */
$pizza = new Margherita( new CheeseTopping, new OnionsTopping );
$pizza->getPrice();
I'd definitely make Pizza a class and not an interface indeed. Then justa
properly executed Decorator Pattern can set, and tell you exactly what
type, toppings and total price this particular pizza would have. I would
not recommend making 'Margherita','CheeseTopping' etc. hardcoded classes..
Unless it remains static after development, it would be a maintenance
nightmare to add/remove/alter different kinds of pizza & toppings. I
assume come kind of interface that gives options for Pizza & Toppings
would be involved, which would mean that any alteration in those requires
altering code & data in several places.
Rather, I'd have a database with a Pizzas table, including name & price,
and a Toppings table, including name & price, and just a 'generic' Pizza
object with the type/name/price in a variable, and either 'decorated'
using the Decorator Pattern with generic Topping objects (which themselves
hold a toppingtype/toppingprice), or just an array of toppings in the
Pizza class itself, so you could do a:
class Pizza{
...
public function getPrice(){
$price = $this->_price;
if(!empty($this->_toppings){
foreach($this->_toppings as &$topping){
$price += $topping->getPrice();
}
}
return $price
}
...
}
... which hardly is any complicated pattern but gets the job done easily.
As long as 'toppings' don't have any profound impact on the 'Pizza' other
then price and actually being added as topping I'd choose this. If they
have other impacts, like changing the output of Pizza::getRecipe(),
Pizza::getBoxSize(), Pizza::getCalories() the Decorator Pattern would
certainly pay out.
--
Rik Wasmus