设计模式之组合模式(Composite)

1、定义


组合模式(Composite Pattern)也叫合成模式,将对象组合成树形结构以表示“整体-部分”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

2、通用类图


image

Component抽象构件角色:定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性。

Leaf叶子构件:叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。

Composite树枝构件:树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构。

3、通用源代码

package Composite;
public abstract class Component {
    //个体和整体都具有的共享
    public void doSomething(){
        //编写业务逻辑
    }
}
package Composite;

import java.util.ArrayList;

public class Composite extends Component{
    //构件容器
    private ArrayList<Component> componentArrayList=new ArrayList<Component>();
    //增加一个叶子构件或树枝构件
    public void add(Component component){
        this.componentArrayList.add(component);
    }
    //删除一个叶子构件或树枝构件
    public void remove(Component component){
        this.componentArrayList.remove(component);
    }
    //获得分支下的所有叶子构件和树枝构件
    public ArrayList<Component> getChileren(){
        return this.componentArrayList;
    }
}
package Composite;

public class Leaf extends Component{
    /*
     * 可以重写父类方法
     *    public void doSomething(){
     *  
     *  }
     */
}
package Composite;

public class Main {
    public static void main(String[] args){
        //创建一个根节点
        Composite root=new Composite();
        root.doSomething();
        //创建一个树枝构件
        Composite branch=new Composite();
        //创建一个叶子节点
        Leaf leaf=new Leaf();
        //建立整体
        root.add(branch);
        branch.add(leaf);
    }
    public static void display(Composite root){
        for(Component c:root.getChileren()){
            if(c instanceof Leaf){//叶子节点
                c.doSomething();
            }else{
                display((Composite)c);
            }
        }
    }
}

posted on 2014-08-18 18:46  limiracle  阅读(172)  评论(0)    收藏  举报

导航