属于对象的结构模式,有时又叫做“部分——整体”模式。组合模式将对象组织到树结构中,可以用来描述整体和部分的关系。组合模式可以使客户端将单纯元素与复合元素同等看待。
组合模式
组合模式把部分和整体的关系用树结构表示出来。组合模式使得客户端把一个个单独的成分对象和由它们复合而成的复合对象同等看待。
例如:一个文件系统就是典型的组合模式系统。下面是常见的Windows文件系统中的一部分。
抽象构件:
abstract class Component {
public abstract void operation();
public void add(Component c) {
throw new UnsupportedOperationException();
}
public void remove(Component c) {
throw new UnsupportedOperationException();
}
public Component getChild(int i) {
throw new UnsupportedOperationException();
}
}
UnsupportedOperationException 是为了 Leaf 在继承之后不用重写该方法,因为这些方法是 Composite 对象需要重写的,而单个对象不需要。
Leaf 类:
class ConcreteComponent1 extends Component {
public void operation() {
System.out.println("operation of concrete component 1 ");
}
}
class ConcreteComponent2 extends Component {
public void operation() {
System.out.println("operation of concrete component 2 ");
}
}
class ConcreteComponent3 extends Component {
public void operation() {
System.out.println("operation of concrete component 3 ");
}
}
组合类:
import java.util.ArrayList;
class Composite extends Component {
private ArrayList<Component> children;
public Composite() {
children = new ArrayList<Component>();
}
public void operation() {
for(Component child: children) {
child.operation();
}
}
public void add(Component c) {
children.add(c);
}
public void remove(Component c) {
children.remove(c);
}
public Component getChild(int i) {
return children.get(i);
}
}
客户端调用:
public class Client {
public static void main(String[] args) {
Component c1 = new ConcreteComponent1();
Component c2 = new ConcreteComponent2();
Component c3 = new ConcreteComponent3();
Component c = new Composite();
c.add(c1);
c.add(c2);
c.add(c3);
c.operation();
c.remove(c2);
c.operation();
}
}
用法
你想表示对象的部分-整体层次结构
你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
组合模式与之前讲的装饰器模式很像,都是通过在类中存储成员变量来完成一些功能上的扩展,那么它们之间有什么不同呢?
每一个装饰器类只有含有一个组件,即没有对象聚合,而每个组合类可以含有多个组件,即 Composite。
装饰器模式倾向于在原有对象的基础上添加新的功能,组合模式倾向于对原有对象的功能进行组合使用。