看书时没太理解,经过这篇博文搞懂了,所以代码也是用的他的,附加一点解释:
由于此例并没有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()
原文:http://www.cnblogs.com/pengsixiong/p/4870357.html