## Object oriented "food factory". ## Implements the "factory method" design pattern class pizza: def __init__(self): self.ingredients = [] self.baseprice = 10.0 self.makebasic() # make basic self.make() # dispatch to specific make ## # default make def makebasic(self): self.ingredients.append("dough") self.ingredients.append("cheese") self.ingredients.append("tomato sauce") # self # default specific make def make(self): 0 # do nothing ## ## pizza BASE class class pepperonipizza(pizza): def __init__(self): pizza.__init__(self) # calls base class constructor def make(self): self.ingredients.append("pepperoni") def price(self): return self.baseprice + 3.0 ## pepperonipizza class cheesepizza(pizza): def __init__(self): pizza.__init__(self) # calls base class constructor # no different make def price(self): return self.baseprice + 1.0 ## cheesepizza class hawaiianpizza(pizza): def __init__(self): pizza.__init__(self) # calls base class constructor def make(self): self.ingredients.append("canadian bacon") self.ingredients.append("pineapple") def price(self): return self.baseprice + 4.0 ## ############## class sandwich: def __init__(self,m=False): self.ingredients = ["bread"] self.baseprice = 6.00 self.mayo = m self.make() # dispatch to specific make # base init def make(self): if self.mayo: self.ingredients.add("mayonnaise") ## default make ## class hamandcheese(sandwich): def __init__(self,m=False): sandwich.__init__(self,m) ## def make(self): self.ingredients.append("ham") self.ingredients.append("cheese") def price(self): return len(self.ingredients)*2 ## class blt(sandwich): def __init__(self,m=False): sandwich.__init__(self,m) ## def make(self): self.ingredients.append("bacon") self.ingredients.append("lettuce") self.ingredients.append("tomato") def price(self): return len(self.ingredients) + 3.0 ## blt ##### mylunch = blt(True) yourlunch = hamandcheese(True) #yourdinner = pepperonipizza(True) #error! can't put mayo on pizza!! #mydinner = chesspizza() # error! class name not found mysnack = hawaiianpizza() #yum! foodorder = [mylunch,yourlunch,mysnack] price =0.0 for f in foodorder: price += f.price() print "pay me $",price print "bon appetite" ############# object adapter pattern: add avocado option to sandwiches class avsandwich(sandwich): def __init__(self,s): self.sand = s # sandwich that will now include avocado self.sand.ingredients.append("avocado") ## def price(self): return self.sand.price() + 1 ## the object adaptor modularly modifies the features of an object regblt = blt() avoblt = avsandwich(blt()) # a blt sandwich with avocado print regblt.price(), avoblt.price()