zoukankan      html  css  js  c++  java
  • 6:装饰模式

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

    由于此例并没有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()。也正是这个挨个调用模拟了一个一个加以装饰的效果。
  • 相关阅读:
    C#中使用MATLAB
    各种插值法及效果图对比
    Visual Studio中你所不知道的智能感知
    C#中使用Surfer
    XCode中连接使用GitHub
    个人作业Week1
    个人作业Week3
    个人作业Week2
    第一次作业——subway
    执行ajax加载页面中的js总结
  • 原文地址:https://www.cnblogs.com/pengsixiong/p/4870357.html
Copyright © 2011-2022 走看看