大话设计模式之装饰模式(python实现)

使用场景

建造过程不稳定,不确定。把所需的功能按照正确的顺序串联起来进行控制。

新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。

定义

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

装饰模式结构图

来自《大话设计模式》

  • Component是定义一个对象接口,可以给这个对象动态添加职责,对应下文python实现中的Persion类
  • Decorator继承Component类,是通过具体装饰类抽象出来的一个类,对应下文python实现中的Finery类
  • ConcreteDecoratorA/ConcreteDecoratorB类,就是具体的装饰对象,继承自Decorator类,动态的给Component添加职责,对应下文python实现中的TShirt/BigTrouser/Sneaker

python实现装饰模式

#coding=utf-8
import os


class Person:
    def __init__(self, name):
        self.name = name

    def show(self):
        print('打扮的' + self.name)


class Finery(Person):
    def __init__(self):
        self.component = None

    def decorate(self, component):
        self.component = component

    def show(self):
        if self.component is not None:
            self.component.show()


class TShirt(Finery):
    def show(self):
        print '大T恤',
        self.component.show()


class BigTrouser(Finery):
    def show(self):
        print '垮裤',
        self.component.show()


class Sneaker(Finery):
    def show(self):
        print '运动鞋',
        self.component.show()


if __name__ == '__main__':
    p = Person('大熊')
    upClothes = TShirt()
    downClothes = BigTrouser()
    shoes = Sneaker()
    upClothes.decorate(p)
    downClothes.decorate(upClothes)
    shoes.decorate(downClothes)
    shoes.show()

  • 执行结果
运动鞋 垮裤 大T恤 打扮的大熊

代码结构图

来自《大话设计模式》

优点

把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。

装饰顺序很重要。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值