python
設計模式
裝飾模式
class Hamberger:
def __init__(self):
self.price = 0
self.meat = ''
def GetPrice(self):
print(self.price)
class PigHamberger(Hamberger):
def __init__(self):
self.price = 35
self.meat = 'Pig'
class BeefHamberger(Hamberger):
def __init__(self):
self.price = 45
self.meat = 'Beef'
class Decorator(Hamberger):
def __init__(self, hamberger):
self.price = hamberger.price
self.meat = hamberger.meat
class EggDecorator(Decorator):
def __init__(self,hamberger):
super().__init__(hamberger)
def GetPrice(self):
self.price += 5
self.meat = self.meat + ' with Egg'
print(self.price)
class CheeseDecorator(Decorator):
def __init__(self, hamberger):
super().__init__(hamberger)
def GetPrice(self):
self.price += 5
self.meat = self.meat + ' with Cheese'
print(self.price)
pigHamberger = PigHamberger()
pigHamberger.GetPrice()
EGG1 = EggDecorator(pigHamberger)
EGG1.GetPrice()
print(EGG1.meat)
EGG2 = EggDecorator(EGG1)
EGG2.GetPrice()
print(EGG2.meat)
C = CheeseDecorator(EGG2)
C.GetPrice()
print(C.meat)
beefHamberger = BeefHamberger()
beefHamberger.GetPrice()
EGG1 = EggDecorator(beefHamberger)
EGG1.GetPrice()
print(EGG1.meat)
EGG2 = EggDecorator(EGG1)
EGG2.GetPrice()
print(EGG2.meat)
C = CheeseDecorator(EGG2)
C.GetPrice()
print(C.meat)
程式碼說明
定義漢堡類別,定義豬肉口味漢堡,定義牛肉口味漢堡,定義裝飾模式,定義加蛋,定義加起司以下為測試
留言
張貼留言