最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第六章
Python 3.x
# -.- 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())