23种设计模式之组合模式

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

 

package designMode.composite;

abstract class Component {
    
    protected String name;
    
    public Component(String name){
        this.name = name;
    }
    
    public abstract void add(Component c);
    
    public abstract void remove(Component c);
    
    public abstract void display(int depth);
}
package designMode.composite;

import org.apache.commons.lang3.StringUtils;

class Leaf extends Component{

    public Leaf(String name) {
        super(name);
    }

    @Override
    public void add(Component c) {
        System.out.println("can't add to a leaf");
    }

    @Override
    public void remove(Component c) {
        System.out.println("can't remove from a leaf");
    }

    @Override
    public void display(int depth) {
        System.out.println(StringUtils.repeat("-", depth)+name);
    }

}
package designMode.composite;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

class Composite extends Component{
    
    private List<Component> children = new LinkedList<Component>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component c) {
        children.add(c);
    }

    @Override
    public void remove(Component c) {
        children.remove(c);
    }

    @Override
    public void display(int depth) {
        System.out.println(StringUtils.repeat("-", depth)+name);
        for (Component component : children) {
            component.display(depth+2);
        }
    }
}
package designMode.composite;

class Test {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        root.add(new Leaf("LeafA"));
        root.add(new Leaf("LeafB"));
        
        Composite comp = new Composite("Composite X");
        comp.add(new Leaf("Leaf XA"));
        comp.add(new Leaf("Leaf XB"));
        
        root.add(comp);
        
        Composite comp2 = new Composite("Composite XY");
        comp2.add(new Leaf("Leaf XYA"));
        comp2.add(new Leaf("Leaf XYB"));
        
        comp.add(comp2);
        
        root.add(new Leaf("Leaf C"));
        
        Leaf leaf = new Leaf("Leaf D");
        root.add(leaf);
        root.remove(leaf);
        
        root.display(1);
    }
}

 

posted @ 2017-08-23 09:23  如果屈原会编程  阅读(178)  评论(0编辑  收藏  举报