首页 > 其他 > 详细

6:装饰模式

时间:2015-10-12 00:33:25      阅读:209      评论:0      收藏:0      [点我收藏+]

看书时没太理解,经过这篇博文搞懂了,所以代码也是用的他的,附加一点解释:

由于此例并没有component,故把本是concretecomponent的person作为component,代码如下:

 1 class Person:
 2     def __init__(self,tname):
 3         self.name = tname
 4     def Show(self):
 5        print("dressed %s" %(self.name))
 6 
 7 class Finery(Person):
 8     componet = None
 9     def __init__(self):
10         pass
11     def Decorate(self,ct):                  #ct参数为类实例型参数
12         self.componet = ct
13     def Show(self):
14         if(self.componet!=None):
15             self.componet.Show()
16 
17 class TShirts(Finery):
18     def __init__(self):
19         pass
20     def Show(self):
21         print("Big T-shirt ")
22         self.componet.Show()
23 
24 class BigTrouser(Finery):
25     def __init__(self):
26         pass
27     def Show(self):
28         print("Big Trouser ")
29         self.componet.Show()
30 
31 
32 p = Person("somebody")
33 bt = BigTrouser()
34 ts = TShirts()              #p,bt,ts都是实例
35 bt.Decorate(p)              #即bt.component=p
36 ts.Decorate(bt)             #即ts.component=bt
37 ts.Show()           #从而挨个调用ts.show(),bt.show(),p.show()

 

6:装饰模式

原文:http://www.cnblogs.com/pengsixiong/p/4870357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!