思維導圖之節點結構
如果要打造一個思維導圖的控件。我們基本可以推斷出這個結構是一個樹形結構。而樹形結構的節點模型是怎樣的呢?它將具備啥屬性呢?
- 指向父節點
- 子節點集合
- 當前的層級
- 是否關閉節點
- 是否當前對焦的節點
由於這個節點是一個抽象的概念,所以我把它看做爲一種泛型,這樣它就可以攜帶更多其他拓展屬性。
根據以上的分析我們可以編寫出節點代碼如下
package com.owant.thinkmap
import java.util.*
/**
* created by Kyle.Zhong on 2020/6/8
* 節點
*/
open class NodeModel<T> {
/**
* 父節點
*/
var parentNode: NodeModel<T>? = null
/**
* 當前節點的數據
*/
var nodeValue: T
/**
* 子節點集合
*/
var childNodes: LinkedList<NodeModel<T>>? = LinkedList<NodeModel<T>>()
/**
* 當前的層級
*/
var float: Int? = 0
/**
* 是否關閉
*/
var close: Boolean? = false
/**
* 是否對焦
*/
var focusing: Boolean? = false
constructor(nodeValue: T) {
this.nodeValue = nodeValue
}
}
測試代碼
package com.owant.thinkmap
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/**
* created by Kyle.Zhong on 2020/6/8
*/
@RunWith(JUnit4::class)
class NodeModelTest {
@Test
fun createNode() {
var rootNode = NodeModel<Person>(Person(100, "Father"));
rootNode.float = 1
rootNode.focusing = true
var child = NodeModel<Person>(Person(12, "Child"))
child.float = 2
child.focusing = false
var child2 = NodeModel<Person>(Person(10, "Child2"))
child2.focusing = false
rootNode.childNodes?.add(child)
rootNode.childNodes?.add(child2)
Assert.assertEquals(rootNode.focusing, true)
Assert.assertEquals(rootNode.childNodes?.get(0)?.focusing, false)
Assert.assertEquals(rootNode.childNodes?.get(0)?.nodeValue?.name, "Child")
Assert.assertEquals(rootNode.childNodes?.get(1)?.nodeValue?.name, "Child2")
}
}