python设计模式(三)--装饰器模式
2016-05-12 00:00
525 查看
摘要: 服饰变幻莫测,采用装饰器而不是继承.
最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第六章
Python 3.x
最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第六章
Python 3.x
[code=plain]# -.- coding:utf-8 -.- # __author__ = 'zhengtong' # 继承的方式面对变幻莫测的服装搭配, 立马凌乱无比. # 其他模式的选型: 建造者模式 # 嗯,虽然建造者模式是内部组装完毕,但是建造者模式要求 # 建造的过程必须是稳定的,而服装搭配的过程是非固定的,所以。。 # 再选择其他的模式: 装饰器模式 # 装饰器模式,动态的给一个对象添加一些额外的职责,就增加功能来说 # 装饰器比生成子类更为灵活. # 最终的效果是解决每个类都单独show()的过程. from functools import wraps def decorate(func, finery): @wraps(func) def wrap(*args, **kwargs): return '{0} {1}'.format(finery, func(*args, **kwargs)) return wrap def big_trouser(func): return decorate(func, "垮裤") def tsherts(func): return decorate(func, "大T恤") def sneaker(func): return decorate(func, "破球鞋") def suit(func): return decorate(func, "西装") def tie(func): return decorate(func, "领带") def leather_shoes(func): return decorate(func, "皮鞋") class Main: def __init__(self, name): self.name = name @big_trouser @tsherts def one(self): print('第一种装扮') return self.show() @leather_shoes @tie @suit def two(self): print('第二种装扮') return self.show() @sneaker @leather_shoes @big_trouser @tie def three(self): print('第三种装扮') return self.show() def show(self): return '装扮的{0}'.format(self.name) if __name__ == '__main__': xc = Main('小菜') print(xc.one()) print(xc.two()) print(xc.three())
相关文章推荐
- python设计模式(四)--代理模式(上)
- python设计模式(四)--代理模式(中)
- 用python 10min手写一个简易的实时内存监控系统
- 用Python写一个简单的监控系统
- python3使用logging日志记录
- Python基础(三) 数据类型
- Python学习---day 1
- python_Day1_基础知识开篇
- (Python学习4)List对象
- Python yield coroutine
- Python的安装与文件类型
- Python自省(反射)----inspect module
- python基础(内置函数+文件操作+lambda)
- python2.x和python3.x中raw_input( )和input( )区别
- Python中if __name__ == "__main__"是什么作用
- python ssh_Rcmd
- python 使用百度语音api
- Python中tile函数的用法
- Python 协程与多任务调度
- 《python灰帽子》学习笔记:写一个windos 调试器(一)