适配器模式之组合模式

设计模式目录
http://blog.csdn.net/fenglailea/article/details/52733435
风.fox

组合模式

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

通用类图

组合模式

组成

  • 抽象构件角色 Component
    定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性
  • 叶子构件 Leaf
    叶子对象,其下再也没有其他的分支,也就是遍历的最小单位
    • 树枝构件 Composite
      树枝对象,他的作用是组合树枝节点和叶子节点形成一个树形结构

通用源码

JAVA

//抽象构件
public abstract class Component{
    // 个体和整体都具有的共享
    public void doSomething(){
        ...
    }
}
// 树枝构件
public class Composite extends Component{
    // 构件容器
    private ArrayList<Component> componentArrayList= new ArrayList<Component>();
    // 增加一个叶子构件或树枝构件
    public void add(Component component){
        this.componentArrayList.add(component);
    }
    //删除一个叶子构件或树枝构件
    public void remove(Component component){
        this.componentArrayList.remove(component);
    }
    //获得分支下的所有叶子构件和树枝构件
    public ArrayList<Component> getChildred(){
        return this.componentArrayList;
    }
}
// 树叶构件
public class Leaf extends Component{
    /**
    * 可以覆写父类方法
    * pulic void doSomething(){}
    */
}
//场景
public class Client{
    public static void main(String[] args){
        //创建一个节点
        Composite root =new Composite();
        root.doSomething();
        //创建一个树枝构件
        Composite branch=new Composite();
        //创建一个叶子节点
        Leaf leaf =new Leaf();
        //建立整体
        root.add(branch);
        branch.add(leaf);
    }
}

优点

高层模块调用简单
节点自有增加

使用场景

维护和展示部分-整体关系的场景
从一个整体中能够独立出部分模块或功能的场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风.foxwho

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值