Python設(shè)計模式之建造者模式實例詳解
本文實例講述了Python設(shè)計模式之建造者模式。分享給大家供大家參考,具體如下:
建造者模式(Builder Pattern):將一個復(fù)雜對象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過程可以創(chuàng)建不同的表示
下面是一個建造者模式的demo
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大話設(shè)計模式
設(shè)計模式——建造者模式
建造者模式(Builder):將一個復(fù)雜對象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過程可以常見不同的表示
特性: 指揮者(Director) 指揮 建造者(Builder) 建造 Product
"""
import abc
class Builder(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def create_header(self):
pass
@abc.abstractmethod
def create_body(self):
pass
@abc.abstractmethod
def create_hand(self):
pass
@abc.abstractmethod
def create_foot(self):
pass
class Thin(Builder):
def create_header(self):
print '瘦子的頭'
def create_body(self):
print '瘦子的身體'
def create_hand(self):
print '瘦子的手'
def create_foot(self):
print '瘦子的腳'
class Fat(Builder):
def create_header(self):
print '胖子的頭'
def create_body(self):
print '胖子的身體'
def create_hand(self):
print '胖子的手'
def create_foot(self):
print '胖子的腳'
class Director(object):
def __init__(self, person):
self.person = person
def create_preson(self):
self.person.create_header()
self.person.create_body()
self.person.create_hand()
self.person.create_foot()
if __name__=="__main__":
thin = Thin()
fat = Fat()
director_thin = Director(thin)
director_fat = Director(fat)
director_thin.create_preson()
director_fat.create_preson()
運行結(jié)果:
瘦子的頭
瘦子的身體
瘦子的手
瘦子的腳
胖子的頭
胖子的身體
胖子的手
胖子的腳
上面類的設(shè)計如下圖:

指揮者Director 調(diào)用建造者Builder的對象 具體的建造過程是在Builder的子類中實現(xiàn)的
更多關(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è)計有所幫助。
相關(guān)文章
Python 如何優(yōu)雅的將數(shù)字轉(zhuǎn)化為時間格式的方法
這篇文章主要介紹了Python 如何優(yōu)雅的將數(shù)字轉(zhuǎn)化為時間格式的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
python列表推導(dǎo)式入門學(xué)習(xí)解析
這篇文章主要介紹了python列表推導(dǎo)式入門學(xué)習(xí)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12

