组合模式
组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性,组合模式可以让客户端像修改配置文件一样简单的完成本来需要流程控制语句来完成的功能。
涉及角色:
1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件。
2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。
关系如下图(来自百度):

组合模式让你可以优化处理递归或分级数据结构。有许多关于分级数据结构的例子,使得组合模式非常有用武之地。关于分级数据结构的一个普遍性的例子是你每次使用电脑时所遇到的:文件系统。文件系统由目录和文件组成。每个目录都可以装内容。目录的内容可以是文件,也可以是目录。按照这种方式,计算机的文件系统就是以递归结构来组织的。如果你想要描述这样的数据结构,那么你可以使用组合模式Composite。
举个例子,假设文件夹A下面有两个TXT文件和子文件夹 文件夹B,文件夹B下又有两个TXT文件;关系如下图:

我们怎么用组合模式表示呢?
首先定义组合中的对象声明接口(Component)
public interface Component { public void add(Component component); public void remove(Component component); public Component getComponent(int i); public void prin(); public String getname(); }
然后定义:叶子结点对象(leaf),也就是具体的菜单项(如:A.TXT\B.TXT);
public class Leaf implements Component{ private String name; public Leaf(String name) { this.name=name; } public String getname() { return name; } public void prin() { System.out.println(name); } //不相关的方法省略 }
最后定义: 枝节点(Composite),也就是菜单(如文件夹A,文件夹B)
public class Composite implements Component{ private String name; private List<Component>list=new ArrayList<Component>(); public Composite(String name) { this.name=name; } public void add(Component component) { list.add(component); } public void remove(Component component) { list.remove(component); } public Component getComponent(int i) { return list.get(i); } public void prin() { System.out.println(getname()); for (Component component : list) { component.prin(); } } public String getname() { return name; } }
测试如下
public class Test { public static void main(String[] args) { Component composite=new Composite("文件夹A"); Component comosite2=new Composite("文件夹B"); Component leaf=new Leaf("a.txt"); Component leaf2=new Leaf("b.txt"); comosite2.add(leaf); comosite2.add(leaf2); composite.add(leaf); composite.add(leaf2); composite.add(comosite2); composite.prin(); } }
输出:
文件夹A
a.txt
b.txt
文件夹B
a.txt
b.txt
浙公网安备 33010602011771号