Python设计模式——装饰模式(Decorator Pattern)

import abc
from abc import ABC


class Beverage(metaclass=abc.ABCMeta):
    description = "Unknown Description"

    def getDescription(self):
        return self.description

    @abc.abstractmethod
    def cost(self):
        raise NotImplementedError


class CondimentDecorator(Beverage, metaclass=abc.ABCMeta):
    """调料类"""

    @abc.abstractmethod
    def getDescription(self):
        raise NotImplementedError


class Espresso(Beverage):
    """浓缩咖啡"""

    def __init__(self):
        self.description = "Espresso"

    def cost(self):
        return 1.99


class DarkRoast(Beverage):

    def __init__(self):
        self.description = "DarkRoast"

    def cost(self):
        return 2.99


class Mocha(CondimentDecorator):
    beverage = ""

    def __init__(self, beverage):
        self.beverage = beverage

    def getDescription(self):
        return self.beverage.getDescription() + ", Mocha"

    def cost(self):
        return 2 + self.beverage.cost()


if __name__ == '__main__':
    beverage = Espresso()
    print(beverage.getDescription(), " $", beverage.cost())
    beverage2 = DarkRoast()
    beverage2 = Mocha(beverage2)
    print(beverage2.getDescription(), " $", + beverage2.cost())

 

你可能感兴趣的:(Python设计模式)