设计模式(11)-组合模式(Composite)

设计模式(10)-桥接模式(Bridge) 【设计模式(11)-组合模式(Composite)】11、组合模式(Composite)
组合模式有时又叫部分-整体模式,在处理类似树形结构的问题时比较方便
例子:

//节点类 public class TreeNode { private String name; private TreeNode parent; private Vector children = new Vector(); public TreeNode(String name){ this.name = name; }public String getName() { return name; }public void setName(String name) { this.name = name; }public TreeNode getParent() { return parent; }public void setParent(TreeNode parent) { this.parent = parent; }//添加孩子节点 public void add(TreeNode node){ children.add(node); }//删除孩子节点 public void remove(TreeNode node){ children.remove(node); }//取得孩子节点 public Enumeration getChildren(){ return children.elements(); } }

//表示一个树状结构 public class Tree {TreeNode root = null; public Tree(String name) { root = new TreeNode(name); } }

//测试类 public class Test{public static void main(String[] args) { Tree tree = new Tree("A"); TreeNode nodeB = new TreeNode("B"); TreeNode nodeC = new TreeNode("C"); nodeB.add(nodeC); tree.root.add(nodeB); System.out.println("build the tree finished!"); } }






    推荐阅读