设计模式学习之如何组合一个树(组合模式)

 定义:       

        组合模式也叫合成模式,有时又叫做部分-整体模式,主要是用来描述部分与整体的关系。对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。现在生活中有很多这样的例子,比如:公司的职级体系,文件的目录接口,包括我们的亲属关系等待,都可以用这种树形结构的设计模式来设计。

组合模式的角色:

  • Component:抽象定义的基础组件,包含组合对象默认的方法和属性,叶子和树枝构件都继承于它。
  • Leaf:叶子构件或者叫叶子对象,遍历的最小单位,也就是树形结构中最末端的部分
  • Composite:树枝构件或者加树枝对象,它是组合模式的核心构件,它的作用是组合树枝节点和叶子节点形成一个树形结构。

简单实现:

/**
 * 组合模式
 * 抽象工具
 * 基础构建
 */
public abstract class Component {
    //职级
    protected String rankName;
    public Component(String rankName){
        this.rankName = rankName;
    }
    //增加一个职级
    protected abstract void add(Component component);
    //减少一个职级
    protected abstract void delete(Component component);

}

package com.compose;

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

/**
 * 组合模式
 * 核心构架
 */
public class Composite extends Component{

    private List<Component> components = new ArrayList<>();
    public Composite(String usrName) {
        super(usrName);
    }

    @Override
    protected void add(Component component) {
        components.add(component);
    }

    @Override
    protected void delete(Component component) {
        components.remove(component);

    }
    //获取所有字节点
    public List<Component> getChildren(){
        return this.components;
    }
}

/**
 * 组合模式
 * 叶子节点
 */
public class Leaf extends Component{

    List<Component> components = new ArrayList<>();
    public Leaf(String usrName) {
        super(usrName);
    }

    @Override
    protected void add(Component component) {
        components.add(component);
    }

    @Override
    protected void delete(Component component) {
        components.remove(component);

    }
}

/**
 * 组合模式
 */
public class TestCompose {
    public static void main(String[] args) {

                Composite root = new Composite("经理");
                root.add(new Leaf("助理"));

                Composite composite1 = new Composite("副经理");
                root.add(composite1);
                Composite composite2 = new Composite("组长1");
                composite1.add(composite2);
                composite2.add( new Leaf("组员1"));
                show(root);

    }

    public static  void show(Composite root){
        System.out.println("-------" + root.rankName);
        for (Component c:root.getChildren()) {
            if(c instanceof Leaf){
                System.out.println("叶子节点----" + c.rankName);
            }else {
                show((Composite)c);
            }
        }
    }
}

//打印结果
-------经理
----助理
-------副经理
-------组长1
----组员1

总结:

组合模式需要在特定的场景中使用,表示成树状结构,组合模式中所有节点都是 基础组件Component,这更有利于高层模块中的调用,无需关注它是单个对象还是整体组合,而且如果不是叶子节点都可以获取到它的子节点。同时,扩展节点十分方便,只需要知道它的父节点。

 参考《设计模式之禅》秦小波著

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值