组合模式

组合模式

组合模式的定义:
主要用来描述部分和整体的关系,其定义如下:
Compose objects into tree structure to represent part-whole hierarchies. Composite lets clients treat
individual objects and compositions of objects uniformly.
将对象组合成树形结构以表示“部分——整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

组合模式

组合模式的角色:
1.Component抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性
2.Leaf叶子构件
叶子对象,其下面也没有其他分支,也就是遍历的最小单位
3.Composite树枝构件
树枝对象,它的作用是组合树枝节点或叶子节点形成一个树形结构

//抽象构件
public abstract class Component{
    public void doSomething(){
        //
    }
}
//树枝构件
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> getChildren(){
        return this.componentArrayList;
    }
}

//树叶构件
public class Leaf extends Component{
    /*
     *可以覆盖父类方法
    public void doSomething(){
    
    }
    */
}

//场景类
public class Client{
    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.getChildren()){
            if(c instanceof Leaf){//叶子节点
                c.doSomething();
            }else{//树枝节点
                display((Composite)c);
            }
        }
    }
}