组合模式:将对象组合成树形结构以表示‘部分-整体’的层次结构,组合模式使得用户对当个对象或者组合对象的使用具有一致性。
组合模式类图:
Component: 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component;
Leaf:叶节点,没有子节点只有叶节点的功能
Composite:定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除
(remove)等。
使用场景:需求中是体现部分和整体曾侧的结构是,以及希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就可以用组合模式。
Component接口:
public interface Component {
public void add(Component c);
public void remove(Component c);
public void display(int depth);
}
Composite 类:
import java.util.ArrayList;
import java.util.List;
public class Composite implements Component {
private List<Component> list = new ArrayList<Component>();
@Override
public void add(Component c) {
if(c != null) {
list.add(c);
}
}
@Override
public void remove(Component c) {
if(list.contains(c)) {
list.remove(c);
}
}
@Override
public void display(int depth) {
System.out.println("this is " + depth);
for(Component c : list) {
c.display(depth + 1);
}
}
}
Leaf 类:
public class Leaf implements Component{
@Override
public void add(Component c) {
// TODO Auto-generated method stub
}
@Override
public void remove(Component c) {
// TODO Auto-generated method stub
}
@Override
public void display(int depth) {
System.out.println("this is leaf " + depth);
}
}
Client类:
import org.junit.Test;
public class Client {
@Test
public void componentTest() {
Component leaf1 = new Leaf();
Component leaf2 = new Leaf();
Component leaf3 = new Leaf();
Component c = new Composite();
c.add(leaf1);
c.add(leaf2);
c.add(leaf3);
c.display(0);
}
}
透明方式和安全模式:
在Component中声名所用来管理子对象的方法,不止是Composite中包含这个管理方法,子节点中也包含,但是子节点中的这些方法是没有任何意义的,这是透明方式;
安全方式:在COmponent接口中不去声名add和Remove方法,那么子类的leaf也就不需要去实现它,而是在Composite声名所有用来管理子类对象的方法。
安全模式由于不够透明,所以树叶和树枝类将不具有相同的几口,客户端的调用需要做相应的判断,带来了不便;