0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[DecoratorPattern]wikiのサンプルコードをpython3実装

Posted at

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())

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?