组合模式
组合多个对象形成树形结构以表示具有 “整体—部分” 关系的层次结构。
组合模式的关键是定义了一个抽象构件类,它既可以代表叶子,又可以代表容器,而客户端针对该抽象构件类进行编程,无须知道它到底表示的是叶子还是容器,可以对其进行统一处理。同时容器对象与抽象构件类之间还建立一个聚合关联关系,在容器对象中既可以包含叶子,也可以包含容器,以此实现递归组合,形成一个树形结构。
例子:文件目录
包含文件夹和文件两种类型
透明组合模式
抽象构件角色中声明了所有用于管理成员对象的方法
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| interface Component { fun getName(): String = throw UnsupportedOperationException()
fun add(component: Component): Unit = throw UnsupportedOperationException()
fun remove(component: Component): Unit = throw UnsupportedOperationException()
fun print(): Unit = throw UnsupportedOperationException()
fun getContent(): String = throw UnsupportedOperationException() }
class Folder(private val name: String) : Component { private val componentList = ArrayList<Component>()
override fun getName() = name
override fun add(component: Component) = componentList.add(component)
override fun remove(component: Component) = componentList.remove(component)
override fun print() { println(getName()) componentList.forEach { it.print() } } }
class File( private val name: String, private val content: String ) : Component { override fun getName() = name
override fun print() { println(getName()) }
override fun getContent() = content }
|
安全组合模式
在安全组合模式中,只声明了公有方法
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 28 29 30 31
| interface Component { fun getName(): String
fun print() }
class Folder(private val name: String) : Component { private val componentList = ArrayList<Component>()
override fun getName(): String = name
override fun print() { println(getName()) componentList.forEach { it.print() } }
fun add(component: Component) = componentList.add(component)
fun remove(component: Component) = componentList.remove(component) }
class File( private val name: String, private val content: String ) : Component { override fun getName(): String = name
override fun print() = println(getName())
fun getContent() = content }
|