【设计模式】装饰器模式

from abc import ABC, abstractmethod


class PriceComputer(ABC):

    @abstractmethod
    def compute_price(self):
        pass


class Goods(PriceComputer):

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

    def compute_price(self):
        return self.price


class Discount(PriceComputer):

    def __init__(self, price_computer, discount):
        self.price_computer = price_computer
        self.discount = discount

    def compute_price(self):
        return self.price_computer.compute_price() * self.discount


class RedPaper(PriceComputer):

    def __init__(self, price_computer, red_equity):
        self.price_computer = price_computer
        self.red_equity = red_equity

    def compute_price(self):
        return self.price_computer.compute_price() - self.red_equity


class Coupon(PriceComputer):

    def __init__(self, price_computer, coupon_equity):
        self.price_computer = price_computer
        self.coupon_equity = coupon_equity

    def compute_price(self):
        return self.price_computer.compute_price() - self.coupon_equity

if __name__ == '__main__':
    goods = Coupon(RedPaper(Discount(Goods(100), 0.8), 5), 2)
    print(goods.compute_price())
上一篇:什么是计算机


下一篇:在 GitHub 复活 80 年代的游戏代码,它们出自第一本售出百万册的计算机书籍