装饰模式-Python版---穿什么有这么重要?
来源:互联网 发布:性别刻板印象 知乎 编辑:程序博客网 时间:2024/06/08 15:14
装饰模式
模式模式应用于动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。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
- 装饰模式-Python版---穿什么有这么重要?
- 【设计模式】穿什么有这么重要? --- 装饰模式
- 第六章 穿什么有这么重要-装饰模式(读书笔记)
- 第六章 穿什么有这么重要---装饰模式(读书笔记)
- 《大话设计模式》之--第6章 穿什么有这么重要?----装饰模式
- 《大话设计模式》之--第6章 穿什么有这么重要?----装饰模式
- 第6章 穿什么有这么重要?-装饰模式 大话设计模式
- 《大话设计模式》--穿什么有这么重要?--装饰模式<Decorator>(6)
- 大话设计模式-第06章 穿什么有这么重要?--装饰模式
- 穿什么有这么重要吗?————装饰模式
- 第六章 穿什么有这么重要吗?—装饰模式
- 《大话设计模式》——读后感 (6)穿什么有这么重要?——装饰模式
- 《大话设计模式》——读后感 (3)穿什么有这么重要?——装饰模式之理论实例(1)
- 《大话设计模式》——读后感 (3)穿什么有这么重要?——装饰模式之理解实例(2)
- 大话设计模式六:装饰模式(穿什么有那么重要吗)
- 走穿23种设计模式-7装饰模式详解
- 装饰模式(python版)
- 衣服还要一件一件穿——装饰模式
- HTML常用标签之"地图"标签
- iOS调用相机/相册,并使用VPImageViewController(三方库)对图像处理(1)
- Mobile Web前端开发系列-常用技巧
- 蒋炜航:敏捷开发的实战经验
- 客户端上显示csdn上的各类别下的的文章列表 (制作csdn app 三)
- 装饰模式-Python版---穿什么有这么重要?
- NeoKylin_Desktop_Personal搭建本地源
- NT式驱动的动态加载
- View编程(2): invalidate()再探
- MVC笔记
- WPF Binding相关的一些常见方式总结(五)
- Git 常用命令速查表(图文+表格)
- 《Head First 设计模式》之工厂模式
- eclipse更新SDK后显示ADT不匹配解决方法