大話設計模式Python實現-建造者模式


建造者模式(Builder Pattern):將一個復雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示

下面是一個建造者模式的demo

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 __author__ = 'Andy'
 5 
 6 """
 7 大話設計模式
 8 設計模式——建造者模式
 9 建造者模式(Builder):將一個復雜對象的構建與它的表示分離,使得同樣的構建過程可以常見不同的表示
10 特性: 指揮者(Director) 指揮 建造者(Builder) 建造 Product
11 """
12 import abc
13 class Builder(object):
14     __metaclass__ = abc.ABCMeta
15 
16 
17     @abc.abstractmethod
18     def create_header(self):
19         pass
20 
21     @abc.abstractmethod
22     def create_body(self):
23         pass
24 
25     @abc.abstractmethod
26     def create_hand(self):
27         pass
28 
29     @abc.abstractmethod
30     def create_foot(self):
31         pass
32 
33 class Thin(Builder):
34 
35     def create_header(self):
36         print '瘦子的頭'
37 
38     def create_body(self):
39         print '瘦子的身體'
40 
41     def create_hand(self):
42         print '瘦子的手'
43 
44     def create_foot(self):
45         print '瘦子的腳'
46 
47 class Fat(Builder):
48 
49     def create_header(self):
50         print '胖子的頭'
51 
52     def create_body(self):
53         print '胖子的身體'
54 
55     def create_hand(self):
56         print '胖子的手'
57 
58     def create_foot(self):
59         print '胖子的腳'
60 
61 class Director(object):
62 
63     def __init__(self, person):
64         self.person = person
65 
66     def create_preson(self):
67         self.person.create_header()
68         self.person.create_body()
69         self.person.create_hand()
70         self.person.create_foot()
71 
72 
73 if __name__=="__main__":
74     thin = Thin()
75     fat = Fat()
76     director_thin = Director(thin)
77     director_fat = Director(fat)
78     director_thin.create_preson()
79     director_fat.create_preson()

 

上面類的設計如下圖:

指揮者Director 調用建造者Builder的對象 具體的建造過程是在Builder的子類中實現的

 


作者:Andy
出處:http://www.cnblogs.com/onepiece-andy/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM