python 實現裝飾器設計模式

python 裝飾器簡單、基本的實現並不複雜。裝飾器(Decorators)模式類似於繼承,當你需要爲某一個對象添加額外的動作、行爲時,在不改變類的情況下可以使用裝飾器。這篇文就當做一篇水文,本來不想寫,因爲這個專欄是設計模式的多語言基本實現,不涉及過多內容,爲了保證內容完整,所以只能直接塞進來了。

首先我們先新建一個人的基類,並且賦予幾個屬性(名字、性別、頭髮、衣服等),並且由兩個基類,男人和女人:

class People():
    name = ""
    sex=""
    clothes = "沒穿"
    hair="光頭"
    sound_color=""

class Man(People):
    def __init__(self,name):
        self.name=name
        self.sex="男"
 
class Woman(People):
    def __init__(self,name):
        self.name=name
        self.sex="女" 

由於類以及新建,不進行改變,使用裝飾器進行行爲狀態添加,是用裝飾器。
新建一個裝飾器基類,設置好裝飾器方法,gethair 與 getclothes,再寫兩個類 hairDecorator與 dressedDecorator 繼承於 exteriorDecorator,在裝飾器 hairDecorator 中使對象長出頭髮,原有對象中頭髮的屬性值是關頭,在 dressedDecorator 中使對象穿上衣服,原有屬性爲沒穿衣服。裝飾器類如下:

class exteriorDecorator():#外形裝飾基
    def gethair(self):
        pass
    def getclothes(self):
        pass
        
class hairDecorator(exteriorDecorator):#頭髮裝飾
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def gethair(self):
        return str(self.people.name)+" 長出頭髮"

class dressedDecorator(exteriorDecorator):#外衣裝飾
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def getclothes(self):
        return str(self.people.name)+" 穿上外衣"

以上裝飾器在初始化時傳入了類對象。接下來新建一個對象小明與裝飾器對象:

xiaoming=Man("小明")
xiaomingHariD=hairDecorator(xiaoming)

使用hairDecorator 方法裝飾小明的頭髮,使用 dressedDecorator 裝飾小明的上衣:

xiaomingHariD=hairDecorator(xiaoming)
xiaomingdressedD=dressedDecorator(xiaoming)

最後進行輸出:

print(xiaomingHariD.gethair())
print(xiaomingdressedD.getclothes())

結果如下:
在這裏插入圖片描述
完整代碼如下:

class People():
    name = ""
    sex=""
    clothes = "沒穿"
    hair="光頭"
    sound_color=""

class Man(People):
    def __init__(self,name):
        self.name=name
        self.sex="男"
 
class Woman(People):
    def __init__(self,name):
        self.name=name
        self.sex="女" 


class exteriorDecorator():#外形裝飾基
    def gethair(self):
        pass
    def getclothes(self):
        pass
        
class hairDecorator(exteriorDecorator):#頭髮裝飾
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def gethair(self):
        return str(self.people.name)+" 長出頭髮"

class dressedDecorator(exteriorDecorator):#外衣裝飾
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def getclothes(self):
        return str(self.people.name)+" 穿上外衣"

xiaoming=Man("小明")
print(xiaoming.name)
xiaomingHariD=hairDecorator(xiaoming)
xiaomingdressedD=dressedDecorator(xiaoming)
print(xiaomingHariD.gethair())
print(xiaomingdressedD.getclothes())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章