知识点树与组合设计模式:
知识点树在库中根据编号来实现,在java类中用组合模式来实现。
uml图:
JAVA实现代码:
AbstractNode抽象类:
package test.GOF.composite;
public abstract class AbstractNode {
public abstract boolean add(AbstractNode node);
public abstract boolean remove(AbstractNode node);
public abstract void diplay(int deth);
}
LeafNode类:
package test.GOF.composite;
public class LeafNode extends AbstractNode {
private String name = "";
public LeafNode() {
}
public LeafNode(String name) {
this.name = name;
}
@Override
public boolean add(AbstractNode node) {
System.out.println("是叶子了,没有子节点了!");
return false;
}
@Override
public void diplay(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("-");
}
System.out.println(this.name);
}
@Override
public boolean remove(AbstractNode node) {
System.out.println("没有子节点,不可删除!");
return false;
}
}
Node类:
package test.GOF.composite;
import java.util.ArrayList;
import java.util.List;
public class Node extends AbstractNode {
String name = "";
List<AbstractNode> child = new ArrayList<AbstractNode>();
public Node() {
}
public Node(String name) {
this.name = name;
}
@Override
public boolean add(AbstractNode node) {
return child.add(node);
}
@Override
public void diplay(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("-");
}
System.out.println(this.name);
for (AbstractNode node : child) {
node.diplay(depth + 1);
}
}
@Override
public boolean remove(AbstractNode node) {
return child.remove(node);
}
}
MainTest类:
package test.GOF.composite;
public class MainTest {
public static void main(String[] args) {
LeafNode leaf1 = new LeafNode("010101");
LeafNode leaf2 = new LeafNode("010102");
LeafNode leaf3 = new LeafNode("010103");
Node node1 = new Node("0101");
node1.add(leaf1);
node1.add(leaf2);
node1.add(leaf3);
leaf1 = new LeafNode("0102");
leaf2 = new LeafNode("0103");
Node root = new Node("01");
root.add(node1);
root.add(leaf1);
root.add(leaf2);
root.diplay(0);
}
}