組合模式(Composite Pattern):將對象組合成成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性.
下面是一個組合模式的demo:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 __author__ = 'Andy' 5 6 """ 7 大話設計模式 8 設計模式——組合模式 9 組合模式(Composite Pattern):將對象組合成成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性. 10 """ 11 12 # 抽象一個組織類 13 class Component(object): 14 15 def __init__(self, name): 16 self.name = name 17 18 def add(self,comp): 19 pass 20 21 def remove(self,comp): 22 pass 23 24 def display(self, depth): 25 pass 26 27 # 葉子節點 28 class Leaf(Component): 29 30 def add(self,comp): 31 print '不能添加下級節點' 32 33 def remove(self,comp): 34 print '不能刪除下級節點' 35 36 def display(self, depth): 37 strtemp = '' 38 for i in range(depth): 39 strtemp += strtemp+'-' 40 print strtemp+self.name 41 42 43 # 枝節點 44 class Composite(Component): 45 46 def __init__(self, name): 47 self.name = name 48 self.children = [] 49 50 def add(self,comp): 51 self.children.append(comp) 52 53 def remove(self,comp): 54 self.children.remove(comp) 55 56 def display(self, depth): 57 strtemp = '' 58 for i in range(depth): 59 strtemp += strtemp+'-' 60 print strtemp+self.name 61 for comp in self.children: 62 comp.display(depth+2) 63 64 if __name__ == "__main__": 65 #生成樹根 66 root = Composite("root") 67 #根上長出2個葉子 68 root.add(Leaf('leaf A')) 69 root.add(Leaf('leaf B')) 70 71 #根上長出樹枝Composite X 72 comp = Composite("Composite X") 73 comp.add(Leaf('leaf XA')) 74 comp.add(Leaf('leaf XB')) 75 root.add(comp) 76 77 #根上長出樹枝Composite X 78 comp2 = Composite("Composite XY") 79 #Composite X長出2個葉子 80 comp2.add(Leaf('leaf XYA')) 81 comp2.add(Leaf('leaf XYB')) 82 root.add(comp2) 83 # 根上又長出2個葉子,C和D,D沒張昊,掉了 84 root.add(Leaf('Leaf C')) 85 leaf = Leaf("Leaf D") 86 root.add(leaf) 87 root.remove(leaf) 88 #展示組織 89 root.display(1)
上面類的設計如下圖:
應用場景:
在需要體現部分與整體層次的結構時
希望用戶忽略組合對象與單個對象的不同,統一的使用組合結構中的所有對象時
作者:Andy
出處:http://www.cnblogs.com/onepiece-andy/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。