SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
One solution is to create an individual class for every combination. Each class describes the drink and is responsible for the cost etc. The resulting menu is huge, and a part of the class diagram would look something like this:
The key to using this method is to find the particular combination you want. So, once you’ve found the drink you would like, here is how you would use it, as shown in the CoffeeShop class in the following code:
# Decorator/nodecorators/CoffeeShop.py # Coffee example with no decorators class Espresso: pass class DoubleEspresso: pass class EspressoConPanna: pass class Cappuccino: def __init__(self): self.cost = 1 self.description = "Cappucino" def getCost(self): return self.cost def getDescription(self): return self.description class CappuccinoDecaf: pass class CappuccinoDecafWhipped: pass class CappuccinoDry: pass class CappuccinoDryWhipped: pass class CappuccinoExtraEspresso: pass class CappuccinoExtraEspressoWhipped: pass class CappuccinoWhipped: pass class CafeMocha: pass class CafeMochaDecaf: pass class CafeMochaDecafWhipped: def __init__(self): self.cost = 1.25 self.description = \ "Cafe Mocha decaf whipped cream" def getCost(self): return self.cost def getDescription(self): return self.description class CafeMochaExtraEspresso: pass class CafeMochaExtraEspressoWhipped: pass class CafeMochaWet: pass class CafeMochaWetWhipped: pass class CafeMochaWhipped: pass class CafeLatte: pass class CafeLatteDecaf: pass class CafeLatteDecafWhipped: pass class CafeLatteExtraEspresso: pass class CafeLatteExtraEspressoWhipped: pass class CafeLatteWet: pass class CafeLatteWetWhipped: pass class CafeLatteWhipped: pass cappuccino = Cappuccino() print((cappuccino.getDescription() + ": $" + `cappuccino.getCost()`)) cafeMocha = CafeMochaDecafWhipped() print((cafeMocha.getDescription() + ": $" + `cafeMocha.getCost()`))
And here is the corresponding output:
Cappucino: $1.0 Cafe Mocha decaf whipped cream: $1.25
You can see that creating the particular combination you want is easy, since you are just creating an instance of a class. However, there are a number of problems with this approach. Firstly, the combinations are fixed statically so that any combination a customer may wish to order needs to be created up front. Secondly, the resulting menu is so huge that finding your particular combination is difficult and time consuming.