目录
0、定义
1、组合模式的三种角色
2、组合模式的UML类图
3、示例代码
0、定义
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使用户对单个对象和组合对象的使用具有一致性。
1、组合模式的三种角色
- 抽象组件(Component):是一个接口(抽象类),该接口(抽象类)定义了个体对象和组合对象需要实现的关于操作其子节点的方法,比如add()、remove()以及getChild()等方法。抽象组件也可以定义个体对象和组合对象用于操作其自身的方法。
- Composite节点(Composite Node):实现Component接口类的实例,Composite节点不仅实现Component接口,而且可以含有其他Composite节点或Leaf节点的引用。
- Leaf节点(Leaf Node):实现Component接口类的实例,Leaf节点实现Component接口,不可以含有其他Composite节点或Leaf节点的引用,因此,叶节点在实现Component接口有关操作子节点的方法时,比如add()、remove()和getChild()方法,可让方法抛出一个异常,也可以实现为空操作。
2、组合模式的UML类图
3、示例代码
抽象组件
package xyz.jangle.design.composite;
/*** 抽象组件* @author Administrator**/
public interface Component {public void add(Component component);public void remove(Component component);public Component getChild(int i);public void opration();}
Composite节点(组合节点)
package xyz.jangle.design.composite;import java.util.Iterator;
import java.util.LinkedList;
/*** Composite节点* @author Administrator**/
public class Composite implements Component {private LinkedList<Component> child;public Composite() {super();child = new LinkedList<Component>();}@Overridepublic void add(Component component) {child.add(component);}@Overridepublic void remove(Component component) {child.remove(component);}@Overridepublic Component getChild(int i) {return child.get(i);}@Overridepublic void opration() {System.out.println(this+" Composite to do something");Iterator<Component> iterator = child.iterator();while(iterator.hasNext()) {Component component = iterator.next();component.opration();}}}
Leaf节点(叶子节点)
package xyz.jangle.design.composite;public class Leaf implements Component {@Overridepublic void add(Component component) {}@Overridepublic void remove(Component component) {}@Overridepublic Component getChild(int i) {return null;}@Overridepublic void opration() {System.out.println(this + " Leaf to do something");}}
客户端(使用)
package xyz.jangle.design.composite;public class AppMain18 {public static void main(String[] args) {Composite firstNode = new Composite();Leaf leaf1 = new Leaf();Leaf leaf2 = new Leaf();Composite childNode = new Composite();Leaf childLeaf1 = new Leaf();Leaf childLeaf2 = new Leaf();firstNode.add(leaf1);firstNode.add(leaf2);firstNode.add(childNode);childNode.add(childLeaf1);childNode.add(childLeaf2);firstNode.opration();System.out.println("-------------");childNode.opration();}}
输出结果
xyz.jangle.design.composite.Composite@659e0bfd Composite to do something
xyz.jangle.design.composite.Leaf@2a139a55 Leaf to do something
xyz.jangle.design.composite.Leaf@15db9742 Leaf to do something
xyz.jangle.design.composite.Composite@6d06d69c Composite to do something
xyz.jangle.design.composite.Leaf@7852e922 Leaf to do something
xyz.jangle.design.composite.Leaf@4e25154f Leaf to do something
-------------
xyz.jangle.design.composite.Composite@6d06d69c Composite to do something
xyz.jangle.design.composite.Leaf@7852e922 Leaf to do something
xyz.jangle.design.composite.Leaf@4e25154f Leaf to do something