装饰模式-Python版---穿什么有这么重要?

45 篇文章 0 订阅
装饰模式
模式模式应用于动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。

Component类

class Component:
    def Operation(self):
        pass

ConcreteComponent类

class ConcreteComponent(Component):
    def Operation(self):
        pass

Decorator类

class Decorator(Component):
    def SetComponent(self, component):
        self.component = component
    def Operation(self):
	if self.component != null :
            self.component.Operation(self)
ConcreteDecoratorA 和ConcreteDecoratorB 类

class ConcreteDecoratorA(Decorator):
    __addedstate = null
    def Operation(self):
        Decorator.Operation(self)
        self.__addedstate = "New state"

class ConcreteDecoratorB(Decorator):
    def Operation(self):
        Decorator.Operation(self)
        self.__AddedBehavior(self)
    def __AddedBehavior(self)
	pass
客户端主程序

if __name__ == "__main__":
    cc = ConcreteComponent()    ##实例化ConcreteComponent
    cdA = ConcreteDecoratorA()  
    cdB = ConcreteDecoratorB()
    cdA.SetComponent(cc)          ##用cdA装饰cc
    cdB.SetComponent(cdA)         ##用cdB装饰cdA
    cdB.Operation()               ##执行cdB的Operation方法

装饰模式是利用SetComponent来对对象进行包装的。每个装饰对象的实现和如何用这个对象分离开。每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。

下图是对人装饰的UML关系图

class Person:
    def __init__(self, name):
        self.name = name
    def Show(self):
        print "dressed is %s" %(self.name)

class Finery(Person):
    component = None
    def Decorate(self, component)	
        self.component = component	
    def Show(self):
        if self.component != None:
            self.component.Show()

class TShits(Finery):
    def Show(self):
        print "T-Shits"
	self.component.Show()

class BigTrousers(Finery):
    def Show(self):
        print "Trousers"
        self.component.Show()

if __name__ == "__main__":
    p = Person("SomeBody")
    ts = TShits()	
    bts = BigTrousers()
    ts.Decorate(p)
    bts.Decorate(ts)
    bts.Show()

装饰模式是为已有功能动态的添加更多功能的一种方式。当系统需要新功能的时候,是向旧的类中添加新的代码。这些新的代码通常祈祷装饰原有核心职责或主要行为。

装饰模式有效的类的核心职责和装饰功能区分开,而且可以去除相关类汇总的重复的装饰逻辑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值