Python_装饰模式

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

装饰模式结构图

在这里插入图片描述

开发过程中什么时候会用到装饰模式

在系统需要新功能的时候,是向旧的类中添加新的代码。这些新的代码通常装饰了原有类的核心职责或主要行为。这样子做的好处,有效地把类的核心职责和装饰功能区分开了。

参照UML的结构图,设计一个带有装饰模式的事例代码。

class Person:
    """Component"""
    def operation(self, name):
        pass


class Student(Person):
    """ConcreteComponent"""
    def operation(self, name):
        print(name)


class Decorator(Person):
    """Decorator"""
    component = Person()

    # 利用set_person 来对对象进行包装的
    def set_component(self, component):
        self.component = component

    def operation(self, name):
        pass


class DecoratorA(Decorator):
    """ConcreteDecorator"""
    name = "装饰器A"

    def eat_something(self):
        print("eat_something:"+self.name)

    def operation(self, name):
        # 旧有代码的核心逻辑
        self.component.operation(name)
        # 新增加的代码
        self.eat_something()


class DecoratorB(Decorator):
    name = "装饰器B"

    """ConcreteDecorator"""
    def operation(self, name):
        # 旧有的核心逻辑
        self.component.operation(name)
        # 新增加的逻辑
        print(self.name)


if __name__ == "__main__":
    student = Student()
    decorator_a = DecoratorA()
    decorator_a.set_component(student)
    decorator_a.operation("decorator_a:"+"裤衩")

    decorator_b = DecoratorB()
    decorator_b.set_component(decorator_a)
    decorator_b.operation("decorator_b:"+"帽子")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值