HeadFirst设计模式_读书笔记_009_ 组合模式
程序员文章站
2022-05-04 17:47:30
...
组合模式:允许将对象组合成树形结构来表现“整体/部分”的结构,让用户可以用一致的方式处理个别对象以及组合对象。
public abstract class Node { protected String name; protected String desc; public Node(String desc, String name) { this.name = name; this.desc = desc; } public void addChild(Node node) { throw new UnsupportedOperationException(); } public void removeChild(Node node) { throw new UnsupportedOperationException(); } public Node getChild(int index) { throw new UnsupportedOperationException(); } public Iterator createIterator() { throw new UnsupportedOperationException(); } public void print() { } }
public class Leaf extends Node { public Leaf(String desc, String name) { super(desc, name); } public void print() { System.out.print("-name:" + name + "-desc:" + desc); System.out.println(); } }
public class NodeItem extends Node { public NodeItem(String desc, String name) { super(desc, name); this.childs = new ArrayList<Node>(); } private List<Node> childs; public void addChild(Node node) { this.childs.add(node); } public void removeChild(Node node) { this.childs.remove(node); } public Node getChild(int index) { return childs.get(index); } public Iterator createIterator() { return this.childs.iterator(); } public void print() { System.out.println("-name:" + name + "-desc:" + desc); for(Node child: childs) { child.print(); } } }
上一篇: 2021-07-01