设计模式之组合模式
2012-12-08 17:14
204 查看
适用于:树结构。整体部分结构。
典型例子:文件夹和文件;JSON库的设计;Swing的容器和组件;
运行结果:
访问根容器:
容器1
叶子1
容器2
叶子2
叶子3
访问容器节点:
容器2
叶子2
叶子3
访问容器节点:
叶子1
典型例子:文件夹和文件;JSON库的设计;Swing的容器和组件;
import java.util.ArrayList; import java.util.List; public class Test3 { public static void main(String[] args) { Component l1 = new Leaf("叶子1"); Component l2 = new Leaf("叶子2"); Component l3 = new Leaf("叶子3"); Component c1 = new Composite("容器1"); Component c2 = new Composite("容器2"); // c1相当于根容器 c1.add(l1); c1.add(c2); c2.add(l2); c2.add(l3); // 访问根容器。则可以访问到所有节点。 (整体) System.out.println("访问根容器:"); c1.operation(); // 也可以直接访问容器节点或叶子节点。 (部分) System.out.println("\n访问容器节点:"); c2.operation(); System.out.println("\n访问容器节点:"); l1.operation(); } } interface Component { void operation(); // 集合操作方法。 // 如果定义在这里,叫做透明的组合模式。如果在客户端需要面向抽象编程,需要使用该种模式。 // 如果定义在容器节点,则叫做安全的组合模式。 void add(Component c); void remove(Component c); Component getChild(int i); } // 叶子节点 class Leaf implements Component { private String name; public Leaf(String name) { this.name = name; } public void operation() { System.out.println(this.name); } // 集合操作方法。叶节点不支持这些操作。 public void add(Component c) { throw new UnsupportedOperationException(); } public Component getChild(int i) { throw new UnsupportedOperationException(); } public void remove(Component c) { throw new UnsupportedOperationException(); } } // 容器类 class Composite implements Component { private String name; public Composite(String name) { this.name = name; } // 持有抽象组件类集合。这样既可以包含叶节点,又可以继续包含容器节点。 private List<Component> children = new ArrayList<Component>(); // 递归遍历 public void operation() { System.out.println(this.name); for (Component c : children) { c.operation(); } } // 集合操作方法 public void add(Component c) { children.add(c); } public Component getChild(int i) { return children.get(i); } public void remove(Component c) { children.remove(c); } }
运行结果:
访问根容器:
容器1
叶子1
容器2
叶子2
叶子3
访问容器节点:
容器2
叶子2
叶子3
访问容器节点:
叶子1
相关文章推荐
- 设计模式之组合模式(Composite)
- Android设计模式系列-组合模式
- 设计模式之组合模式
- 【设计模式】组合模式
- 【设计模式 - 8】之组合模式(Composite)
- [Python设计模式] 第19章 分公司=部门?——组合模式
- C#设计模式——组合模式(Composite Pattern)
- 设计模式之组合模式(卷八)
- 代码设计模式之组合模式(Composite)
- JavaScript 设计模式 – 第一部分: 单例模式、组合模式和外观模式
- 设计模式 3 —— 迭代器和组合模式(迭代器)
- JUnit|测试驱动|组合设计模式
- 设计模式-组合模式
- 温故而知新:设计模式之组合模式(Composite)
- 设计模式系列十 迭代器模式 组合模式介绍
- c#设计模式-组合模式
- 测试类图Head First 设计模式 (九) 迭代器与组合模式(Iterator & Composite pattern) C++实现
- 组合设计模式(CompositePattern)
- JavaScript 设计模式之组合模式解析
- 16. 星际争霸之php设计模式--组合模式