美文网首页
结构型-装饰器模式(Decorator Pattern)

结构型-装饰器模式(Decorator Pattern)

作者: 木叶苍蓝 | 来源:发表于2023-03-05 13:57 被阅读0次

引入

小摊上卖手抓饼,烧饼,火烧一类的都选择加生菜,火腿,牛肉片,鸡蛋等。
老板做好的一个饼热气腾腾的,不能直接拿给顾客,要问顾客的喜好,加不加其他东西,顾客说加牛肉片,这时候旁边的老板娘在饼上加牛肉片,然后装入袋子中,然后收钱。这里面刚刚做好的热气腾腾的烧饼或者手抓饼就是具体的构件,加生菜,火腿,牛肉片,鸡蛋等 放入包装袋 这就是装饰器。

定义

抽象构件
具体构件
抽象装饰类
具体装饰类

角色

装饰模式,动态地给一个对象添加一些额为的职责,就增加功能来说,装饰模式比生成子类更为灵活。

装饰器优点

  1. 装饰器类和被装饰器的类是独立的,降低耦合度。
  2. 装饰模式是继承模式的一种替代方案。

装饰器缺点

  1. 会产生很多小对象

装饰器的使用场景

  1. 想给一个类增加功能,但是又不想修改原来的代码。
  2. 类的核心功能不变,只是需要添加新功能的时候使用。

示例代码

#小摊上卖手抓饼和火烧,手抓饼5块一个,火烧6块一个,可以加辣椒酱,生菜,鸡蛋,牛肉片,火腿片
#辣椒酱免费,生菜多加1元,鸡蛋多加2元,牛肉片多加5元,火腿片多加4元
#顾客根据自己需要进行组合选择
class Bing:
    name = ""
    price = 0.0

    def getPrice(self):
        return self.price

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

    def getName(self):
        return self.name

class HandHeldCake(Bing):
    def __init__(self):
        self.name = "手抓饼"
        self.price = 5

class HuoShao(Bing):
    def __init__(self):
        self.name = "火烧"
        self.price = 6

class decorator:
    def getName(self):
        pass
    def getPrice(self):
        pass

class spicyDecorator(decorator):
    def __init__(self, decorator):
        self.decorator = decorator
    def getName(self):
        return "+spicy"
    def getPrice(self):
        return 0

class vegatableDecorator(decorator):
    def __init__(self, decorator):
        self.decorator = decorator
    def getName(self):
        return "+生菜"
    def getPrice(self):
        return 1

class eggDecorator(decorator):
    def __init__(self, decorator):
        self.decorator = decorator
    def getName(self):
        return  "+鸡蛋"
    def getPrice(self):
        return 2

class beefDecorator(decorator):
    def __init__(self, decorator):
        self.decorator = decorator
    def getName(self):
        return "+牛肉片"
    def getPrice(self):
        return 5

class peikonDecorator(decorator):
    def __init__(self, decorator):
        self.decorator = decorator
    def getName(self):
        return "+火腿片"
    def getPrice(self):
        return 4

if __name__=='__main__':
    hs=HuoShao()
    szb=HandHeldCake()
    print(hs.getName(),hs.getPrice())
    egg=eggDecorator(hs)
    print(hs.getName(),egg.getName(),hs.getPrice()+egg.getPrice())
    beef=beefDecorator(egg)
    print(hs.getName(),egg.getName(),beef.getName(),hs.getPrice()+egg.getPrice()+beef.getPrice())

相关文章

网友评论

      本文标题:结构型-装饰器模式(Decorator Pattern)

      本文链接:https://www.haomeiwen.com/subject/qkmrqdtx.html