昨天太趕,跟本沒時間好好理解
合成模式由三個部件組成
依照做法還有分
/**
* Component:抽象層,提供介面定義行為
*/
abstract class Component(var name: String) {
abstract fun add(component: Component)
abstract fun remove(component: Component)
abstract fun show(depth: Int): String
}
/**
* Composite:樹支,擁有樹葉
*/
class Composite(name: String) : Component(name) {
private val child: ArrayList<Component> = ArrayList()
override fun add(component: Component) {
child.add(component)
}
override fun remove(component: Component) {
child.remove(component)
}
override fun show(depth: Int): String {
val text = StringBuilder()
for (i in 0 until depth) {
text.append("-")
}
text.append("Composite name:$name")
for (component in child) {
val show = component.show(depth + 1)
text.append("\n")
text.append(show)
}
return text.toString()
}
}
/**
* Leaf:樹葉,結構最末端
*/
class Leaf(name: String) : Component(name) {
override fun add(component: Component) {
Log.d("TAG", "樹葉不可新增")
}
override fun remove(component: Component) {
Log.d("TAG", "樹葉不可移除")
}
override fun show(depth: Int): String {
val text = StringBuilder()
for (i in 0 until depth) {
text.append("-")
}
text.append("Leaf name:$name")
return text.toString()
}
}
@Test
fun show() {
val member = Composite("會員系統");
val name = Composite("姓名")
val age = Composite("年齡")
val level = Composite("等級")
member.add(name)
member.add(age)
member.add(level)
name.add(Leaf("Andy"))
name.add(Leaf("Leigh"))
age.add(Leaf("30"))
age.add(Leaf("25"))
level.add(Leaf("Gold"))
level.add(Leaf("Silver"))
assertEquals("合成模式測試", member.show(0))
}
Composite name:會員系統
-Composite name:姓名
--Leaf name:Andy
--Leaf name:Leigh
-Composite name:年齡
--Leaf name:30
--Leaf name:25
-Composite name:等級
--Leaf name:Gold
--Leaf name:Silver