组合模式
定义
组合模式(Composite)
:将对象组合成树形结构以表示’部分-整体‘的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性(整体与部分可以被一致对待
)
UML图
基本实现代码
Component
:为组合中声明对象的接口,在适当的情况下,实现所有类共有接口的默认行为。提供可用于访问和管理子部件的接口。
/**
* @create on 2020/8/23 22:42
* @description 为组合对象声明接口
* @author mrdonkey
*/
abstract class Component(val name: String) {
/**
* 添加部件
*/
abstract fun add(component: Component)
/**
* 移除部件
*/
abstract fun remove(component: Component)
/**
* 展示当前部件
*/
abstract fun display(depth: Int)
}
Leaf
:叶子节点对象,叶子节点没有子节点。(都是一个组件(节点),无子节点)
/**
* @create on 2020/8/23 22:47
* @description 叶子节点
* @author mrdonkey
*/
class Leaf(name: String) : Component(name) {
override fun add(component: Component) {
println("cannot add from a leaf")
}
override fun remove(component: Component) {
println("cannot remove from a leaf")
}
override fun display(depth: Int) {
println(Array(depth) { "-" }.joinToString(" ") + name)
}
}
Composite
:有枝节点对象,用来存储子部件,(都是一个组件(节点,只是它有子节点))
/**
* @create on 2020/8/23 22:47
* @description 枝节点
* @author mrdonkey
*/
class Composite(name: String) : Component(name) {
//孩子
private val children = arrayListOf<Component>()
override fun add(component: Component) {
children.add(component)
}
override fun remove(component: Component) {
children.remove(component)
}
override fun display(depth: Int) {
println(Array(depth) { "-" }.joinToString(" ") + name)//输出本身
for (child in children) {//遍历其孩子
child.display(depth + 2)
}
}
}
Client
:客户端
class Client {
companion object {
@JvmStatic
fun main(args: Array<String>) {
//构建根节点
val root = Composite("root")
root.add(Leaf("Leaf A"))
root.add(Leaf("Leaf B"))
//根上长出分支X
val compositeX = Composite("Composite X")
compositeX.add(Leaf("Leaf XA"))
compositeX.add(Leaf("Leaf XB"))
root.add(compositeX)
//分支X再长出分支
val compositeXY = Composite("Composite XY")
compositeXY.add(Leaf("Leaf XYA"))
compositeXY.add(Leaf("Leaf XYB"))
compositeX.add(compositeXY)
//根部又长出叶子
root.add(Leaf("Leaf C"))
//显示大树的样子
root.display(1)
}
}
}
输出
:
-root
- - -Leaf A
- - -Leaf B
- - -Composite X
- - - - -Leaf XA
- - - - -Leaf XB
- - - - -Composite XY
- - - - - - -Leaf XYA
- - - - - - -Leaf XYB
- - -Leaf C
组合模式的优点以应用
-
优点:
- 基本对象可以被组合层更复杂的组合对象,而这个组合对象又可以被组合,这样不断地递归走下去,在客户的代码中,任何用到基本对象的地方都可以使用组合对象(客户可以一致的使用组合结构和单个对象,
整体与部分可以被一致对待
)。
- 基本对象可以被组合层更复杂的组合对象,而这个组合对象又可以被组合,这样不断地递归走下去,在客户的代码中,任何用到基本对象的地方都可以使用组合对象(客户可以一致的使用组合结构和单个对象,
-
应用:
-
需体现部分与整体的层次的结构时
-
希望用户可以忽略组合对象和单个对象的不同,同一地使用组合结构中的所有对象时
整体与部分可以被一致对待
。如,Android,View像是叶子节点、ViewGroup像是枝节点,构建视图就是一种组合模式。
-