3 结构型模式之 - 组合模式

九路
• 阅读 1207

组合模式的介绍

物以类聚组合模式,结构型模式之一,组合模式比较简单,它将一组相似的对象看作一个对象处理,并根据一个树状结构来组合对象,然后提供一个统一的方法去访问相应的对象,以此忽略掉对象与对象集合之间的差别。

组合模式的定义

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

组合模式的使用场景

表示对象的部分-整体层次结构时,从一个整体中能够独立出部分模块或者功能的场景

下面是组合模式的能用代码 首先要有一个节点的抽象类 代码如下:

/**
 * 透明组合模式
 */
public abstract class Component {
    protected String name;

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

    //具体的逻辑由子类来实现
    public abstract void doSomething();

    //添加一个节点
    public abstract void addChild(Component child);

    //移除一个节点
    public abstract void removeChild(Component child);

    //获取一个节点
    public abstract Component getChild(int index);

}

叶子节点:

/**
 * 叶子节点
 */
public class Leaf extends Component{

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

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

    @Override
    public void addChild(Component child) {
        throw new UnsupportedOperationException("叶子节点没有子节点");
    }

    @Override
    public void removeChild(Component child) {
        throw new UnsupportedOperationException("叶子节点没有子节点");
    }

    @Override
    public Component getChild(int index) {
        throw new UnsupportedOperationException("叶子节点没有子节点");
    }
}

具有叶子节点的节点:

/**
 * 具有叶子节点的节点
 */
public class Composite extends Component{

    private ArrayList<Component> components = new ArrayList<>();

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

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

    //增
    @Override
    public void addChild(Component child) {
        components.add(child);
    }

    //删
    @Override
    public void removeChild(Component child) {
        components.remove(child);
    }

    //查
    @Override
    public Component getChild(int index) {
        return components.get(index);
    }
}

使用的时候可以构造一个根节点,支干节点和几个叶子节点:下面是客户端用法

/**
 * 客户端测试类
 */
public class Client {
    public static void test(){

        //构造一个根节点
        Composite root = new Composite("root");

        //构造两个枝干节点
        Composite branch1 = new Composite("branch1");
        Composite branch2 = new Composite("branch2");

        //构造两个叶子节点
        Leaf leaf1 = new Leaf("left1");
        Leaf leaf2 = new Leaf("left2");

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

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


        root.doSomething();
    }
}

组合模式在android源码中典型的应用注是View和ViewGroup,ViewGroup本身也是一个View,但是和View不同的是,ViewGroup里面可以包含其它子View以及ViewGroup

点赞
收藏
评论区
推荐文章

暂无数据