组合模式-composite

将对象组合成树形结构以表示“整体-部分”的层次结构。composite是的用户对单个对象和组合对象的使用具有一致性

这里写图片描述

组合模式关键定义了一个抽象类或者接口,既可以代表元素又可以代表部分整体,而客户端是针对该接口进行编程。因此,客户端不需要知道是元素还是部分整体,对其统一进行处理。

代码

Main

public class Main {

    public static void main(String[] args) {
        Component l1=new Left();
        Component l2=new Left();
        Component l3=new Left();
        Component l4=new Left();
        
        Component c1=new Composite();
        Component c2=new Composite();
        c1.add(l1);c1.add(l2);
        c1.add(c2);
        c2.add(l3);c2.add(l4);
        c1.each();
    }

}

abs:Component

public abstract class Component {

    abstract public void operation();
    abstract public void add(Component c);
    abstract public void remove(Component c);
    abstract public Component getChild(int i);
    abstract public void each();
}

imp:Composite

public class Composite extends Component {
    
    private ArrayList list=new ArrayList();

    @Override
    public void operation() {
        System.out.println("this is composite");
    }

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

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

    @Override
    public Component getChild(int i) {
        return this.list.get(i);
    }
    
    public void each(){
        System.out.println("this is composite");
        for(int i=0;i

imp:Left

public class Left extends Component {

    @Override
    public void operation() {
        System.out.println("--this is left opertaion");
    }

    @Override
    public void add(Component c) {
        // TODO Auto-generated method stub

    }

    @Override
    public void remove(Component c) {
        // TODO Auto-generated method stub

    }

    @Override
    public Component getChild(int i) {
        return null;
    }

    @Override
    public void each() {
        System.out.println("==this is left,no child");
    }

}

你可能感兴趣的:(组合模式-composite)