建造者模式,也是一種創建新對象的設計方法,和C++中的虛函數很類似,但是用到了python自身的虛基類ABCMeta。
1.應用場景:
? ? ?某個類中的函數較多,且實現比較復雜,很多時候需要繼承的子類重載或者重新定義邏輯;
2.背景基礎:
? ? 由于用到python中虛函數,需要了解abc模塊中的ABCMeta和python中類創建對象時的__metaclass__屬性含義。
一般地,在某個類中如果定義__metaclass__=something時,簡單地說是,創建對象時,會首先找到__metaclass__所指向的對象something,然后使用該對象進行創建對象。
3.代碼:
#coding:utf-8
from abc import ABCMeta,abstractmethod
class Builder():
__metaclass__=ABCMeta
@abstractmethod
def draw_head(self):
pass
@abstractmethod
def draw_body(self):
pass
class Thin(Builder):
def draw_body(self):
print("Draw Thin Body")
def draw_head(self):
print("Draw Thin Head.")
class Fat(Builder):
def draw_body(self):
print("Draw Fat Body")
def draw_head(self):
print("Draw fat Head.")
class Director():
def __init__(self,person):
self.person = person
def draw(self):
self.person.draw_body()
self.person.draw_head()
if __name__ == "__main__":
fat=Fat()
thin=Thin()
director_thin=Director(thin)
director_thin.draw()
director_fat=Director(fat)
director_fat.draw()
#output:
Draw Thin Body
Draw Thin Head.
Draw Fat Body
Draw fat Head.
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
