意图
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象
和组合对象的使用具有一致性。
适用性
以下情况使用Composite模式:
• 你想表示对象的部分-整体层次结构。
• 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。、
效果
Composite模式
• 定义了包含基本对象和组合对象的类层次结构 基本对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,这样不断的递归下去。客户代码中,任何用到基本对象的地方都可以使用组合对象。
• 简化客户代码 客户可以一致地使用组合结构和单个对象。通常用户不知道 (也不关心)处理的是一个叶节点还是一个组合组件。这就简化了客户代码 , 因为在定义组合的那些类中不需要写一些充斥着选择语句的函数。
• 使得更容易增加新类型的组件 新定义的Composite或Leaf子类自动地与已有的结构和客户代码一起工作,客户程序不需因新的Component类而改变。
• 使你的设计变得更加一般化 容易增加新组件也会产生一些问题,那就是很难限制组合中的组件。有时你希望一个组合只能有某些特定的组件。使用Composite时,你不能依赖类型系统施加这些约束,而必须在运行时刻进行检查。
Composite模式的类图
Jdk中组合模式的使用 java.awt组合模式使用 public class Container extends Component { /** * The number of components in this container. * This value can be null. * @see #getComponent * @see #getComponents * @see #getComponentCount */ int ncomponents; /** * The components in this container. * @see #add * @see #getComponents */ Component component[] = new Component[0]; 。。。。。。 public Component getComponent(int n) { synchronized (getTreeLock()) { if ((n < 0) || (n >= ncomponents)) { throw new ArrayIndexOutOfBoundsException("No such child: " + n); } return component[n]; } } ...... public Component add(Component comp) { addImpl(comp, null, -1); return comp; } /** * Adds the specified component to this container. * This is a convenience method for {@link #addImpl}. * <p> * This method is obsolete as of 1.1. Please use the * method <code>add(Component, Object)</code> instead. * @see #add(Component, Object) */ public Component add(String name, Component comp) { addImpl(comp, name, -1); return comp; } ...... } 2. java.util.Map#putAll(Map) public abstract class AbstractMap<K,V> implements Map<K,V> …… public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); }