组合模式屏蔽了部分和整体的差异,让单个对象和组合对象的使用具有一致性。
涉及角色:
1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component
子部件。
2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。
Component
先定义一个文件和文件夹的统一接口(因为文件和文件夹都有open()方法)
public interface Component
{
public void open();
}
Leaf
文件相当于leaf
public class Leaf implements Component
{
@Override
public void open()
{
System.out.println("Leaf doSomething");
}
}
Composite
文件夹相当于composite
public class Composite implements Component
{
List<Component> childs = new ArrayList<Component>();
public void add(Component child)
{
this.childs.add(child);
}
public void remove(Component child)
{
this.childs.remove(child);
}
public Component getChild(int i)
{
return this.childs.get(i);
}
@Override
public void doSomething()
{
for (Component child : childs)
child.doSomething();
}
}
总结: 不论是文件,还是文件夹,对用户来说,都有统一的open()方法
组合模式能够非常好地处理层次结构