二维树型描述信息转换为内存中树型结构数据
把id,parentId,name,url结构的二维信息转换为内存中的树型结构对象
java类:
Node为容器接口,定义容器的规则
TreeNode为Node容器的实现类,有自己内部的存储结构
NodeService为对容器操作的接口
NodeLoader类通过NodeService类填充容器数据
public interface Node { public String getId(); public String getParentId(); public Node[] getChild(); public Object getValue(); public void setId(String id); public void setParentId(String parentId); public void setChildNode(Node[] childNode); public void setValue(Object object); } public class TreeNode implements Node { private String id; private String parentId; private Node[] childNode; private Object value; //geters, setters methods } public interface NodeService { public Node getRoot(); public Node[] getChild(Node node); } public class NodeLoader { NodeService nodeService ; public Node load(NodeService nodeService) { this.nodeService = nodeService ; Node node = nodeService.getRoot(); setChild(node); return node; } private void setChild(Node node) { Node[] childNode = nodeService.getChild(node); node.setChildNode(childNode); if (null == childNode) { return; } for (int i = 0; i < childNode.length; i++) { setChild(childNode[i]); } } }
以菜单树型结构数据为例
Menu为具体的数据结构,作为Node的Object类型的value
MenuNodeService为NodeService接口的实现
public class Menu { private String name ; private String url ; private String description ; private String order ; //geters, setters methods public class MenuNodeService implements NodeService{ public Node getRoot(){ Node rnode = MenuDao.getRootNode(); return rnode ; } public Node[] getChild(Node node){ Node[] rnodes = MenuDao.getChildNode(Node node); return rnodes ; } }
测试代码
public class TestMenuTree { public static void main(String[] args){ NodeLoader loader = new NodeLoader(); NodeService nodeSerive = new MenuNodeService(); Node node =loader.load(nodeSerive); print(node); } public static void print(Node node){ if(node.getChild() == null || node.getChild().length == 0) return ; for(int i = 0 ; i<node.getChild().length ; i ++){ log(((Menu)(node.getChild()[i].getValue())).getName()); print(node.getChild()[i]); } } public static void log(String s){ System.out.println(s); } }
希望大家提出意见,提高扩展性和执行效率
相关推荐
jzlixiao 2020-07-29
Leonwey 2020-06-01
singer 2019-12-13
doubinning 2019-12-02
lmseohy 2015-06-17
ciqingloveless 2019-03-21
olyqcool 2015-06-17
GuangkuoDing 2012-02-06
anningzhu 2017-07-18
liushuibufuqin 2017-12-12
allentony 2018-06-19
xinhao 2018-05-15
Amonos 2018-04-13
chouliqingke 2018-04-03
Fourierrr 2018-02-08