知识点树与组合模式

 知识点树与组合设计模式:

知识点树在库中根据编号来实现,在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);

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值