组合模式

组合模式(Composite Pattern)

组合模式是一种结构型设计模式,将一组对象组合成树状结构,以便可以像对待一个对象一样来对其进行操作,它包含以下三个类型:

  1. component protocol:确保树中的所有构造都可以以相同的方式处理
  2. leaf:树的组成部分,没有子元素
  3. composite:持有leaf对象和composites的容器

UIView就使用到了组合模式

使用举例

使用组合模式做一个文件系统

1.创建component protocol

1
2
3
4
protocol File {
var name: String { get set }
func open()
}

2.创建leaf objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
final class eBook: File {
var name: String
var author: String
init(name: String, author: String) {
self.name = name
self.author = author
}
func open() {
print("Opening \(name) by \(author) in iBooks...\n")
}
}
final class Music: File {
var name: String
var artist: String
init(name: String, artist: String) {
self.name = name
self.artist = artist
}
func open() {
print("Playing \(name) by \(artist) in iTunes...\n")
}
}

3.创建composite对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
final class Folder: File {
var name: String
lazy var files: [File] = []
init(name: String) {
self.name = name
}
func addFile(file: File) {
self.files.append(file)
}
func open() {
print("Displaying the following files in \(name)...")
for file in files {
print(file.name)
}
print("\n")
}
}

4.使用组合模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let psychoKiller = Music(name: "Psycho Killer", artist: "The Talking Heads")
let rebelRebel = Music(name: "Rebel Rebel", artist: "David Bowie")
let blisterInTheSun = Music(name: "Blister in the Sun", artist: "Violent Femmes")
let justKids = eBook(name: "Just Kids", author: "Patti Smith")
let documents = Folder(name: "Documents")
let musicFolder = Folder(name: "Great 70s Music")
documents.addFile(file: musicFolder)
documents.addFile(file: justKids)
musicFolder.addFile(file: psychoKiller)
musicFolder.addFile(file: rebelRebel)
blisterInTheSun.open()
justKids.open()
documents.open()
musicFolder.open()

其他例子

  1. 公司结构:https://segmentfault.com/a/1190000008151403
  2. 菜单:http://www.cocoachina.com/articles/18319
  3. 树状结构和文件系统:https://www.cnblogs.com/goodboy-heyang/p/5226090.html