0x01 意图
动态的给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
0x02 适用场景
UML类图实例:穿衣服
0x03 代码
# coding:utf-8
import os
import json
################## component类 ##################
class Person(object):
def __init__(self, name):
self.name = name
def show(self):
print "decorate's", self.name
################ decorator抽象类 ################
class Finery(object):
def __init__(self):
self.person = None
def decorate(self, person_obj):
self.person = person_obj
def show(self):
if self.person != None:
self.person.show()
################ decorator具体类 ################
class Tshirts(Finery):
def show(self):
print "------------1"
super(Tshirts, self).show()
class Kz(Finery):
def show(self):
print "------------2"
super(Kz, self).show()
class hehe(Finery):
def show(self):
print "------------3"
super(hehe, self).show()
################## 客户端代码 ##################
cs = Person('caoshuai')
ts = Tshirts()
kkzz = Kz()
he = hehe()
ts.decorate(cs)
kkzz.decorate(ts)
he.decorate(kkzz)
he.show()
################## 输出的结果 ##################
c:\Users\caoshuai\Desktop>python linshi.py
------------3
------------2
------------1
decorate's caoshuai
欢迎关注微信公众号(coder0x00)或扫描下方二维码关注,我们将持续搜寻程序员必备基础技能包提供给大家。
网友评论