组合模式

2021-01-04  本文已影响0人  竖起大拇指

1.什么是组合模式

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

组合模式,也称作部分整体模式。是结构型设计模式之一。组合模式画成图就是数据结构中的树结构,有一个根节点,然后有很多分支。将最顶部的根节点叫做根结构件,将有分支的节点叫做枝干构件,将没有分支的末端节点叫做叶子构件.

2.使用场景

3.UML模式图

image.png

4.实现代码

抽象的节点

public abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }
    public abstract void doSonthing();
}

枝干节点:

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

    @Override
    public void doSonthing() {
        System.out.println(name);
        if (null!=components){
            for (Component c:components) {
                c.doSonthing();
            }
        }
    }

    public void addChild(Component child){
        components.add(child);
    }
    public void removeChild(Component child){
        components.remove(child);
    }
    public Component getChild(int index){
        return components.get(index);
    }

}

叶子节点:

public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void doSonthing() {
        System.out.println(name);
    }
}

客户端调用:

public class CLient {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        Composite branch1 = new Composite("branch1");
        Composite branch2 = new Composite("branch2");
        Composite branch3 = new Composite("branch3");

        Leaf leaf1 = new Leaf("leaf1");
        Leaf leaf2 = new Leaf("leaf2");
        Leaf leaf3 = new Leaf("leaf3");

        branch1.addChild(leaf1);
        branch3.addChild(leaf2);
        branch3.addChild(leaf3);

        root.addChild(branch1);
        root.addChild(branch2);
        root.addChild(branch3);

        root.doSonthing();
    }
}

5.安卓源码中组合模式的实现

组合模式在Android中太常用了,View和ViewGroup就是一种很标准的组合模式:


image.png

在Android的视图树中,容器一定是ViewGroup,只有ViewGroup才能包含其他View和ViewGroup。View是没有容器的。者是一种安全的组合模式

上一篇 下一篇

猜你喜欢

热点阅读