wikiのdecoratorのサンプルコードをpython3.xで実装したコードです。(環境python3.9)
Decorator パターン
元がjavaのため、@propertyは使わず、そのままゲッターで実装しています。
decorator_pattern.py
"""UML
<< Component >>
operation() < -----------------
| | |
Concrete Component Decorator(Component) :use Component
operation() |
Concrete Decorator (Decorator)
operation()
deco = ConcreteDecorator_A(
ConcreteDecorator_B(
ConcreteComponent()
)
)
deco.operation()
"""
from abc import ABC, abstractmethod
# Component
class Price(ABC):
@abstractmethod
def get_value(self) -> int:
pass
# Concrete Component
class PrimePrice(Price):
def __init__(self, value: int) -> None:
self.__value = value
def get_value(self) -> int:
return self.__value
# Decorator
class MarginPrice(Price):
def __init__(self, price: Price):
self._price = price
# Concrete Decorator
class WholeSalePrice(MarginPrice):
def __init__(self, price: Price, advantage: int):
super(WholeSalePrice, self).__init__(price)
self.__advantage = advantage
def get_value(self) -> int:
return self._price.get_value() + self.__advantage
# Concrete Decorator 2
class DoublePrice(MarginPrice):
def get_value(self) -> int:
return self._price.get_value() * 2
if __name__ == '__main__':
prime_price = PrimePrice(100)
print(prime_price.get_value())
whole_sale_price = WholeSalePrice(prime_price, 50)
print((whole_sale_price.get_value()))
# double_sale_price = DoublePrice(prime_price)
double_sale_price = DoublePrice(whole_sale_price)
print(double_sale_price.get_value())