组合模式

323 阅读1分钟

概念

也叫部分整体模式,将一组相似对象看作一个对象处理,并提供一个树状结构来组合对象,然后提供一个统一的方法去访问相应的对象,以此忽略对象与对象集合的差别(View和ViewGroup)

实现方式

  • Component —— 抽象根节点。定义所有类共有接口的缺省行为。(View)
  • Composite —— 定义所有子节点的那些枝干节点(自身还有子节点)的行为。(ViewGroup)
  • Leaf —— 叶子节点(TextView)
public abstract class Component {
    public abstract void fun();
}

public class Composite extends Component{
    private List<Component> components = new ArrayList<>();

    @Override
    public void fun(){
        if(components != null){
            for(Component c : components) {
                c.fun();
            }
        }
    } 

    public void addChild(Component child){
        components.add(child);
    }
    // removeChild(), getChild()
}

public class Leaf extends Component {

    @Override
    public void fun(){
        System.out.println("myname");
    }
}

public class Test {
    public static void main(String[] args){
        Composite root = new Composit();
        Composite branch1 = new Composit();
        Composite branch2 = new Composit();
        Leaf l1 = new Leaf();
        Leaf l2 = new Leaf();

        branch1.addChild(leaf1);
        branch2.addChild(leaf2);
        root.addChild(branch1);
        root.addChild(branch2);
        root.fun();

    }
}