组合模式

模式说明

组合模式组合多个对象形成树形结构以表示“整体-部分”的结构层次。

组合模式对单个对象(叶子对象)和组合对象(组合对象)具有一致性,它将对象组织到树结构中,可以用来描述整体与部分的关系。同时它也模糊了简单元素(叶 子对象)和复杂元素(容器对象)的概念,使得客户能够像处理简单元素一样来处理复杂元素,从而使客户程序能够与复杂元素的内部结构解耦。

模式结构图

程序示例

说明:文件夹和文件

代码:

 1 class IFile(object):
 2     def __init__(self,name):
 3         self._name = name
 4     def Add(self,com):
 5         pass
 6     def Display(self,nDepth):
 7         pass
 8 
 9 class File(IFile):
10     def Add(self,file):
11         print "can't add file"
12     def Display(self,nDepth):
13         strtemp = ""
14         for i in range(nDepth):
15             strtemp = strtemp + "-"
16         strtemp = strtemp + self._name
17         print strtemp
18 
19 class Folder(IFile):
20     def __init__(self, name):
21         super(Folder, self).__init__(name)
22         #self._name = name
23         self._filelist = []
24 
25     def Add(self,file):
26         self._filelist.append(file)
27     def Display(self,nDepth):
28         strtemp = ""
29         for i in range(nDepth):
30             strtemp = strtemp + "-"
31         strtemp = strtemp + self._name
32         print strtemp
33         for file in self._filelist:
34             file.Display(nDepth + 2)
35 
36 if __name__ == "__main__":
37     p = Folder("FolderOne")
38     p.Add(File("FolderOne_file1"))
39     p.Add(File("FolderOne_file2"))
40     
41     p2 = Folder('FolderTwo')
42     p.Add(p2)
43 
44     p1 = Folder("FolderThree")
45     p1.Add(File("FolderThree_file1"))
46     
47     p2.Add(p1)
48     
49     p.Display(1);

运行结果:

参考来源:

http://www.cnblogs.com/chenssy/p/3679190.html

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

原文地址:https://www.cnblogs.com/cotton/p/3931391.html