原文:http://blog.youkuaiyun.com/hackerain/article/details/7563915
定义:
将对象组合成树形结构以表示“部分—整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
组合模式主要用来处理一些具有“容器特征”的对象,即他们在充当对象的同时,又可以作为容器包含其他的多个对象。也就是说组合模式表达的是一种树形的结构,将数据结构中的“树”,用面向对象的方式表现出来了,而且表达的是一种多叉树。
看如下的通用类图:

源代码如下:
- /*
- * 抽象节点,定义所有节点的共性
- */
- public abstract class Component {
- private String data;
- public String getData() {
- return data;
- }
- public void setData(String data) {
- this.data = data;
- }
- }
- /*
- * 叶节点,相当于单个对象
- */
- public class Leaf extends Component {
- }
- /*
- * 分支节点,相当于组合对象
- */
- public class Branch extends Component {
- private ArrayList<Component> components=new ArrayList<Component>();
- public void add(Component component){
- this.components.add(component);
- }
- public void remove(Component component){
- this.components.remove(component);
- }
- public ArrayList<Component> getChildren(){
- return this.components;
- }
- }
- public class Client {
- public static void main(String[] args) {
- //定义根节点
- Branch root=new Branch();
- root.setData("root");
- //分支1
- Branch branch1=new Branch();
- branch1.setData("branch1");
- //分支2
- Branch branch2=new Branch();
- branch2.setData("branch2");
- //叶节点1
- Leaf leaf1=new Leaf();
- leaf1.setData("leaf1");
- //叶节点2
- Leaf leaf2=new Leaf();
- leaf2.setData("leaf2");
- //叶节点3
- Leaf leaf3=new Leaf();
- leaf3.setData("leaf3");
- //叶节点4
- Leaf leaf4=new Leaf();
- leaf4.setData("leaf4");
- root.add(branch1);
- root.add(branch2);
- root.add(leaf1);
- branch1.add(leaf2);
- branch2.add(leaf3);
- branch2.add(leaf4);
- display(root);
- }
- //遍历树,输出数据
- public static void display(Branch root){
- for(Component b : root.getChildren()){
- if(b instanceof Leaf){
- System.out.println(b.getData());
- }
- else{
- System.out.println(b.getData());
- display((Branch)b);
- }
- }
- }
- }
组合模式的优点:
1、一个树形结构中所有节点都是Component,局部和整体对调用者来说没有区别,高层模块不必关心自己处理的是单个对象还是整个组合结构,简化了高层模块的代码。
2、节点增加自由
后序:
对这个模式现在还不是很理解,这不就是树结构的面向对象的表示吗?还有其他的什么深意吗?有待于通过实践加深理解。
4242

被折叠的 条评论
为什么被折叠?



