组合模式

来源:互联网 发布:金元证券软件下载 编辑:程序博客网 时间:2024/06/07 10:29

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

这里写图片描述

componsent抽象构建角色:定义共有的方法和属性
Leaf叶子对象:其下没有分支,是最小的遍历结构
Composite树枝对象:组合树枝节点和叶子节点形成一个树形结构

abstract class Component{    public void doSomeThing() {/    }}//树枝类class Composite extends Component {    //组合模式最重要的就是这个数组,存储一层中所有的树枝,树叶    private ArrayList<Component> componentList = new ArrayList<>();    public void add(Component component) {        this.componentList.add(component);    }    public void remove(Component component) {        this.componentList.remove(component);    }    public ArrayList<Component> getComponent() {        return this.componentList;    }}//叶子类class Leaf extends Component{    @Override    public void doSomeThing() {        super.doSomeThing();    }}public class Test {    public static void main(String[] args){        Composite root = new Composite();        Composite branch = new Composite();        root.add(branch);        Leaf leaf = new Leaf();        branch.add(leaf);        show(root);    }    public static void show(Composite composite) {        for (Component c: composite.getComponent()) {            if(c instanceof Leaf)                c.doSomeThing();            else                show((Composite)c);        }    }}

优点:

1、高层模块调用简单:树枝、树叶有公共的父类,高层模块不需要区分树枝、树叶类。
2、节点自由增加

缺点:

树枝、树叶直接继承Component类,与依赖倒置相违背

应用

维护和展示 部分-整体 关系的场景,比如文件和文件夹的管理
从一个整体中能独立出部分模块或功能的场景