本文實(shí)例講述了Python設(shè)計(jì)模式之裝飾模式。分享給大家供大家參考,具體如下:
裝飾模式(Decorator Pattern):動(dòng)態(tài)的給一個(gè)對象添加一些額外的職責(zé),就增加功能來說,裝飾模式比生成子類更為靈活.
下面是一個(gè)給人穿衣服的過程,使用裝飾模式:
#!/usr/bin/env python# -*- coding:utf-8 -*-__author__ = 'Andy'"""大話設(shè)計(jì)模式設(shè)計(jì)模式——裝飾模式裝飾模式(Decorator Pattern):動(dòng)態(tài)的給一個(gè)對象添加一些額外的職責(zé),就增加功能來說,裝飾模式比生成子類更為靈活.特點(diǎn): 有效的把類的核心職責(zé)和裝飾功能區(qū)分開,而且可以去除相關(guān)類中重復(fù)的裝飾邏輯"""# 定義對象接口class Person(object): def __init__(self,name): self.name = name def show(self): print "裝扮的%s"%self.name#裝飾類class Finery(Person): def __init__(self): pass def Decorate(self,componet): self.componet = componet def show(self): if self.componet != None: self.componet.show()#裝扮——T恤class TShirts(Finery): def __init__(self): pass def show(self): print 'T恤' self.componet.show()#裝扮——大褲衩class BigTrouser(Finery): def __init__(self): pass def show(self): print '大褲衩' self.componet.show()# 裝扮——人字拖class FlipFlops(Finery): def __init__(self): pass def show(self): print '人字拖' self.componet.show()if __name__ == '__main__': p = Person('Andy') ff = FlipFlops() bt = BigTrouser() ts = TShirts() ff.Decorate(p) bt.Decorate(ff) ts.Decorate(bt) ts.show()運(yùn)行結(jié)果:
T恤
大褲衩
人字拖
裝扮的Andy
這幾個(gè)類的設(shè)計(jì)如下圖:

通過一個(gè)個(gè)繼承自裝飾類Finery的對象,實(shí)現(xiàn)給Person類賦予職責(zé)的功能,Person類并不會感知Finery的存在
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選