设计模式(十五)组合模式

组合模式

在这里插入图片描述

组合模式的几个角色:

  • Component 抽象构建角色。 定义参加组合对象的共有方法 和属性。
  • Leaf叶子构件。 叶子对象,其下没有其他的分支。
  • Composite 树枝构件。 树枝对象,他的作用是组合树枝节点和叶子节点形成一个树形结构。
public abstract class Component {

    public void doSomething(){

    }
}

public class Composite extends Component{
    
    private ArrayList<Component> componentArrayList=new ArrayList<>();
    
    public void add(Component component){
        this.componentArrayList.add(component);
    }
    
    public void remove(Component component){
        this.componentArrayList.remove(component);
    }
    
    public ArrayList<Component> getChildren(){
        return this.componentArrayList;
    }
}


public class  Leaf extends Component{
    @Override
    public void doSomething(){
        System.out.println("leaf node");
    }
}

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);
    }
    
    public static void display(Composite root){
        
        for(Composite c:root.getChildren()){
            if(c instanceof Leaf){
                ((Leaf) c).doSomething();
            }else{
                display(c);
            }
        }
    }
}

组合模式的优点

  • 高层模块调用简单。 所有的树形结构中的节点就是Component, 高层模块不必关心自己处理的是单个对象还是组合结构,简化了高层模块的代码。
  • 节点自由增加。容易扩展

组合模式的缺点

  • 直接使用了实现类。与依赖倒置,面向接口编程冲突。

组合模式的场景

  • 维护和展示部分–整体关系的场景,如树形菜单,文件和文件夹管理。
  • 从一个整体中能独立出部分模块和功能场景。

组合模式注意事项

只要是树形结构,就要考虑组合模式。 只要是呈现局部和整体的关系的时候,且这种关系比较深,考虑一下组合模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值