设计模式-组合模式

694 阅读2分钟

组合模式的定义

将一组对象组织成树形结构,以表示一种部分-整体的层次结构,组合让客户端(代码使用者)可以统一单个对象和组合对象之间的处理逻辑

组合模式通用类图

  • Component抽象构件角色

    定义参加组合对象的共同方法和属性,可以定义一些默认行为和属性

  • Leaf叶子构件

    叶子对象,其下在没有其他的分支,也就是遍历的最小单位

  • Composite树枝构件

    树枝对象,他的作用是组合树枝节点和树叶节点形成一个树形结构

组合模式案例

package structuralDesgin.combinationPattern;

/**
 * 抽象构件
 */
public abstract class Component {
    //个体和本体都具有的共享
    public void doSomething(){
        //编写业务逻辑
    }
}


package structuralDesgin.combinationPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cuckooYang
 * @create 2020-08-05 17:05
 * @description 树枝构件
 **/

public class Composite extends Component {

    //构件容器
    private List<Component> components = new ArrayList<>();

    //增加一个叶子构件或树枝构件
    public void add(Component component){
        this.components.add(component);
    }
    //删除一个叶子构件或者树枝构件
    public void remove(Component component){
        this.components.remove(component);
    }
    //获得分支下的所有叶子构件和树枝构件
    public List<Component> getChildren(){
        return this.components;
    }

}
package structuralDesgin.combinationPattern;

/**
 * @author cuckooYang
 * @create 2020-08-05 17:12
 * @description 树叶节点
 **/

public class Leaf extends Component {
    //可以覆写父类方法
    public void doSomething(){

    }

}
package structuralDesgin.combinationPattern;

/**
 * @author cuckooYang
 * @create 2020-08-05 17:15
 * @description
 **/

public class Main {
    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( Component c:root.getChildren()){
            if( c instanceof Leaf){
                // 叶 子 节 点
                c.doSomething();
            }else{
                // 树 枝 节 点
                display(( Composite) c);
            }
        }
        }

}

组合模式的优点

  • 高层模块调用简单
  • 节点添加自由

组合模式的缺点

组合模式在场景类中的使用直接使用了实现类,与依赖倒置原则冲突,限制了接口的影响范围