用于把一组相似的对象当作一个单一的对象
涉及角色:
1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component
子部件。
2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除
Node
package design.pattern.component; public abstract class Node { private String name; public Node(String name) { this.name = name; } public String getName() { return this.name; } public abstract Node addNode(Node node) throws RuntimeException; public void print(int depth) { for (int i=0; i<depth; i++) System.out.print(" "); System.out.println(this.name); if (this instanceof Menu) { for (Node node : ((Menu)this).getMenu()) { node.print(depth+1); } } } }
Item
package design.pattern.component; public class Item extends Node { public Item(String name) { super(name); } @Override public Node addNode(Node node) throws RuntimeException { throw new RuntimeException(); } }
Menu
package design.pattern.component; import java.util.ArrayList; import java.util.List; public class Menu extends Node { private List<Node> menu = new ArrayList<>(); public Menu(String name) { super(name); } public List<Node> getMenu() { return menu; } @Override public Node addNode(Node node) throws RuntimeException { menu.add(node); return this; } }
Client
package design.pattern.component; public class Client { public static void main(String[] args) { Node menu = new Menu("1"); menu.addNode(new Item("1.1")); menu.addNode(new Menu("1.2").addNode(new Item("1.2.1"))); menu.addNode(new Item("1.3")); menu.print(0); } }