《Android源码设计模式》读书笔记 (19) 第19章 组合模式

前言

  • 组合模式:部分和整体的模式,结构型设计模式之一.他将一组相似的对象看做一个对象处理,并根据一个树状结构来组合对象.
  • 在android开发过程中,使用得并不多,更适用于对一些界面UI的架构设计上,
  • 组合模式和解释器模式有一定的类同,两者在迭代对象时都涉及递归的调用.

定义

  • 定义:将对象组合成属性结构以表示”部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性.
  • 使用场景:表示对象的部分-整体层次结构,从一个整体能独立出部分模块或功能的场景.

UML类图

这里写图片描述

  • component:抽象根节点,为组合中的类,申明接口对象
/**
 * 抽象根节点
 * @author max
 *
 */
public abstract class Component {
    public String name; //节点名

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

    public abstract void doSomething();
}
  • composite:在component接口中实现与子节点有关的操作.
/**
 * 具体枝干节点
 * @author max
 *
 */
public class Composite extends Component{
    /**
     * 存储节点的容器
     */
    private List<Component> components = new ArrayList<>();

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


    @Override
    public void doSomething() {

    }

    /**
     * 添加子节点
     * @param component 
     */
    public void addChild(Component component){
        components.add(component);
    }

    /**
     * 移除子节点
     * @param component
     */
    public void removeChild(Component component){
        components.remove(component);
    }

    public Component getChildren(int index){
        return components.get(index);
    }
}
  • leaf:在组合中,定义子节点对象的行为
/**
 * 具体叶子节点
 * @author max
 *
 */
public class Leaf extends Component{

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

    @Override
    public void doSomething() {

    }

}
  • client:通过component操作组合节点的对象
/**
 * 客户端调用
 * @author max
 *
 */
public class Client {

    public static void main(String[] args){
        //构造一个根节点
        Composite root = new Composite("haha");

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

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

        //将叶子节点添加至枝干节点中
        branch1.addChild(leaf1);
        branch2.addChild(leaf2);

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

        root.doSomething();//这一步的意义,相当于他下面所有的子类不管有任何差异都会去遍历执行这个方法
    }
}

总结

  • 其实组合模式,就是感觉是父类去遍历子类调用递归方法,分别实现各抽象方法.

源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值