一、定义
The Composite Pattern allows you to
compose objects into tree structures to
represent part-whole hierarchies. Composite
lets clients treat individual objects and
compositions of objects uniformly.
组合模式允许你组合对象到树结构中来代表部分和整体的层次结构。
组合让客户端统一对待单个对象和组合对象。
二、实例
一个公司的组织架构图如下,请使用组合模式来实现:
public abstract class Component {
public void print(String head) {
throw new UnsupportedAddressTypeException();
}
public void add(Component comp) {
throw new UnsupportedAddressTypeException();
}
public void remove(Component comp) {
throw new UnsupportedAddressTypeException();
}
public Component getChild(int i) {
throw new UnsupportedAddressTypeException();
}
}
class Leaf extends Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void print(String head) {
System.out.println(head+"leaf:"+name);
}
}
class Node extends Component {
private String name;
private List<Component> children;
public Node(String name) {
this.name = name;
children=new ArrayList<>();
}
public void print(String head) {
System.out.println(head+"node:"+name);
head=head+"--";
for(Component comp: children) {
comp.print(head);
}
}
public void add(Component comp) {
children.add(comp);
}
public void remove(Component comp) {
children.remove(comp);
}
public Component getChild(int i) {
return children.get(i);
}
}
测试类:
public class Test {
public static void main(String[] args) {
Node root=new Node("CEO");
Leaf c1=new Leaf("财务部经理");
Leaf c2=new Leaf("人事部经理");
Node c3=new Node("技术部经理");
Leaf c4=new Leaf("市场部经理");
root.add(c1);
root.add(c2);
root.add(c3);
root.add(c4);
Node d1=new Node("部门经理");
c3.add(d1);
Node d2=new Node("技术主管1");
Leaf d3=new Leaf("技术主管2");
d1.add(d2);
d1.add(d3);
Leaf e1=new Leaf("软件工程师");
Leaf e2=new Leaf("测试工程师");
Leaf e3=new Leaf("运维工程师");
d2.add(e1);
d2.add(e2);
d2.add(e3);
root.print("");
}
}
输出结果:
node:CEO
--leaf:财务部经理
--leaf:人事部经理
--node:技术部经理
----node:部门经理
------node:技术主管1
--------leaf:软件工程师
--------leaf:测试工程师
--------leaf:运维工程师
------leaf:技术主管2
--leaf:市场部经理
类图:
分析:组合模式描述的是树状结构,叶子结点只有操作方法(其他方法调用会报错UnsupportedOperationException),而非叶子结点可以有孩子节点(可以是叶子,也可以是非叶子结点),使得客户端可以统一使用个体对象和组合对象。
三、总结
组合模式主要应用于树状结构的存储中,如公司的部门和上下级的关系,如JavaGUI的实现。