设计模式-(11)组合模式 (swift版)

时间:2023-03-10 06:49:45
设计模式-(11)组合模式 (swift版)

一,概念
  组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。

  意图: 将对象组合成树形结构以表示”部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

  主要解决: 它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。

  何时使用:  
    1. 您想表示对象的部分-整体层次结构(树形结构)。 
    2. 您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。

  如何解决: 树枝和叶子实现统一接口,树枝内部组合该接口。

  关键代码: 树枝内部组合该接口,并且含有内部属性 List,里面放 Component。

二,结构图

  设计模式-(11)组合模式 (swift版)

  

三,DEMO

  设计模式-(11)组合模式 (swift版)

Component

@objc protocol TreeProtocol {
var trees: Array<TreeProtocol> {get} func doSomething()
@objc optional func addChild(child: TreeProtocol)
@objc optional func removeChild(child: TreeProtocol)
@objc optional func getChildren(index: Int) -> TreeProtocol
@objc optional func clear()
}

Composite

class Tree: TreeProtocol {

    var trees: Array<TreeProtocol>

    init() {
self.trees = Array<TreeProtocol>()
}
func doSomething() { }
func addChild(child: TreeProtocol) {
self.trees.append(child)
}
func removeChild(child: TreeProtocol) { }
func getChildren(index: Int) -> TreeProtocol {
return self.trees[index]
}
func clear() {
self.trees.removeAll()
}
}

Leaf

class Leaf: TreeProtocol {  

    var trees: Array<TreeProtocol> 

    init() {
self.trees = Array<TreeProtocol>()
}
func doSomething() { }
}

Composite,Leaf 指一类结点,并不是唯一,其中 Leaf 是无子结点,也可以说是 Composite 的一种特殊情况。结合 UIView 的代码,再看上面代码,应该可以进一步加深理解组合模式。