合成模式:有时候也成为 部分-整体模式。合成模式将对象组织到树结构中,可以用来描述整体和部分的关系。合成模式可以是客户端将单纯元素与复合元素同等看待。
合成模式分为安全式合成模式和透明式合成模式
下面看安全式的合成模式:管理聚集的方法只出现在树枝构建类中,而不出现在树叶构建类中。
抽象构建:
package com.javapatterns.composite; public interface Component { Composite getComposite(); void sampleOperation(); }
树叶构建:
package com.javapatterns.composite; public class Leaf implements Component { public Composite getComposite(){ // Write your code here return null; } public void sampleOperation(){ // Write your code here } }
树枝构建:
package com.javapatterns.composite; import java.util.Vector; import java.util.Enumeration; public class Composite implements Component { public Composite getComposite() { return this; } public void sampleOperation() { java.util.Enumeration enumeration = components(); while (enumeration.hasMoreElements()) { ((Component)enumeration.nextElement()).sampleOperation(); } } public void add(Component component) { componentVector.addElement(component); } public void remove(Component component) { componentVector.removeElement(component); } public Enumeration components() { return componentVector.elements(); } private Vector componentVector = new java.util.Vector(); }
透明式的合成模式:
抽象构建:
package com.javapatterns.composite.transparent; import java.util.Enumeration; public interface Component { void sampleOperation(); Composite getComposite(); void add(Component component); void remove(Component component); Enumeration components(); }
树叶构建:
package com.javapatterns.composite.transparent; import java.util.Enumeration; import java.util.Vector; public class Leaf implements Component { public void sampleOperation() { // Write your code here } public void add(Component component) { componentVector.addElement(component); } public void remove(Component component) { componentVector.removeElement(component); } public Composite getComposite() { // Write your code here return null; } public Enumeration components() { // Write your code here return null; } /** * @associates <{Component}> * @link aggregation * @supplierCardinality 0..* */ private Vector componentVector = new java.util.Vector(); }
树枝构建:
package com.javapatterns.composite.transparent; import java.util.Vector; import java.util.Enumeration; public class Composite implements Component { public Composite getComposite() { return this; } public void sampleOperation() { java.util.Enumeration enumeration = components(); while (enumeration.hasMoreElements()) { ((Component)enumeration.nextElement()).sampleOperation(); } } public void add(Component component) { componentVector.addElement(component); } public void remove(Component component) { componentVector.removeElement(component); } public Enumeration components() { return componentVector.elements(); } private Vector componentVector = new java.util.Vector(); }