Java设计模式(十一)组合模式

组合模式

定义

组合模式也称为整体-部分模式,它的宗旨是就通过将单个对象(叶子节点)和组合对象(树枝结点)用相同的接口进行标识,使得客户对单个对象和组合对象的使用具有一致性,属于结构型模式。

组合模式:具有相同的生命周期,一般用来描述整体与部分的关系,它将对象组织到树形结构中,最顶层的结点称为根结点,根结点下面可以包含树枝结点和叶子结点,树枝结点下边又可以包含树枝结点和叶子结点。
根结点与树枝结点本质上是同一种数据类型,可以作为容器使用,而叶节点与树枝结点在语义上不属于同一中类型,但是在组合模式中,这个树形结构中的对象都是同一种类型,带来的一个好处就是客户无需辨认是树枝结点还是叶子结点,而是可以直接操作,给客户带来极大的便利。

组合对象和被组合对象都应该统一地接口实现或者统一地父类抽象。

角色
  1. 抽象根结点(Component):定义系统各层次的共有方法和属性,可以预先定义一些默认行为和属性;
  2. 树枝结点(Composite):定义树枝结点的行为,存储子节点,组合树枝结点和叶子结点形成一个数结构;
  3. 叶子结点(leaf):叶子结点对象,其下再无分支,是系统层次遍历的最小单位。

组合模式在代码具体实现上,有两种方式,分别为透明组合模式和安全组合模式。

应用场景

当子系统与其内部各个对象层次呈现树形结构时,可以使用组合模式,让子系统内各个对象层次的行为操作具有一致性。客户端使用该子系统内任意一个层次对象时无需进行区分,直接使用通用操作即可。

  1. 系统客户端可以忽略组合对象与单个对象的差异时;
  2. 对象层次具备整机和部分,呈树形结构。

常见的组合模式:树形菜单,操作系统目录结构,公司组织架构。

透明组合模式将公共接口封装到抽象根结点中,那么系统所有结点具备一致性,所有如果当系统绝大多数层次具备相同的公共行为时,采用透明模式(代价:为剩下少数层次结点引入不需要的方法);如果当系统各个层次差异性行为较多或者树节点层次相对稳定时,采用安全组合模式。

透明组合模式
public abstract class CourseComponent {
    public void addChild(CourseComponent courseComponent){
        throw new UnsupportedOperationException("不支持添加操作");
    }

    public void removeChild(CourseComponent courseComponent){
        throw new UnsupportedOperationException("不支持删除操作");
    }

    public String getName(CourseComponent courseComponent){
        throw new UnsupportedOperationException("不支持获取名称操作");
    }

    public double getPrice(CourseComponent courseComponent) {
        throw new UnsupportedOperationException("不支持获取价格操作");
    }

    public void print() {
        throw new UnsupportedOperationException("不支持打印操作");
    }
}
public class Course extends CourseComponent {

    private String name;

    private double price;

    public Course(String name, double price) {
        this.name = name;
        this.price = price;
    }


    @Override
    public String getName(CourseComponent courseComponent) {
        return this.name;
    }

    @Override
    public double getPrice(CourseComponent courseComponent) {
        return this.price;
    }

    @Override
    public void print() {
        System.out.println(name + "(¥" + price + "元)");
    }
}
public class CoursePackage extends CourseComponent {

    private List<CourseComponent> items = new ArrayList<CourseComponent>();
    private String name;
    private Integer level;

    public CoursePackage(String name, Integer level) {
        this.name = name;
        this.level = level;
    }

    @Override
    public void addChild(CourseComponent courseComponent) {
        items.add(courseComponent);
    }

    @Override
    public String getName(CourseComponent courseComponent) {
        return this.name;
    }

    @Override
    public void print() {
        System.out.println(this.name);
        for (CourseComponent item : items){
            if (this.level != null) {
                for (int i = 0; i < this.level ; i++) {
                    System.out.print("  ");
                }
                for (int i = 0; i < this.level; i++) {
                    if (i == 0) {
                        System.out.print("+");
                    }
                    System.out.print("-");
                }
            }
            item.print();

        }
    }
}

 public static void main(String[] args) {
        CourseComponent javaBase = new Course("Java入门课程",2323);
        CourseComponent ai = new Course("人工智能",4000);

        CourseComponent packageCourse = new CoursePackage("Java架构师课程",2);
        CourseComponent design = new Course("Java设计模式", 1500);
        CourseComponent source = new Course("源码分析", 2000);

        packageCourse.addChild(design);
        packageCourse.addChild(source);

        CourseComponent cataLog = new CoursePackage("课程目录", 1);
        cataLog.addChild(javaBase);
        cataLog.addChild(packageCourse);
        cataLog.addChild(ai);

        cataLog.print();
    }
}

透明组合模式吧所有的公共方法都定义在Component总,这样做的好处是客户端无需分辨是叶节点和树枝结点,它们剧本完全一致的接口;缺点是叶子结点会集成得到一些它不需要的方法,这与设计原则:接口隔离原则相违背。

安全组合模式

安全组合模式是只规定系统各个层次的最基础的一致行为,而把组合(树枝结点)本身的方法放到自身当中

public abstract class Directory {

    protected String name;

    public Directory(String name) {
        this.name = name;
    }

    public abstract void show();
}

public class File  extends Directory{

    public File(String name) {
        super(name);
    }

    @Override
    public void show() {
        System.out.println(this.name);
    }
}

public class Folder  extends Directory{

    private List<Directory> dirs;

    private Integer level;

    public Folder(String name, Integer level) {
        super(name);
        this.level = level;
        this.dirs = new ArrayList<Directory>();
    }

    @Override
    public void show() {
        System.out.println(this.name);
        for (Directory dir : dirs) {
            if (this.level != null) {
                for (int i = 0; i < this.level ; i++) {
                    System.out.print("  ");
                }
                for (int i = 0; i < this.level; i++) {
                    if (i == 0) {
                        System.out.print("+");
                    }
                    System.out.print("-");
                }
            }
            dir.show();
        }
    }

    public boolean add(Directory dir){
        return this.dirs.add(dir);
    }
}

安全组合模式的好处是接口定义职责清晰,符合设计原则的单一职责原则和接口隔离原则;缺点是客户需要区分树枝结点和叶子结点,这样才能正确处理各个层次的操作,客户端无法依赖抽象,违背了依赖倒置原则。

组合模式在源码中的使用

HashMap中的pullAll()方法;
ArrayList中的addAll()方法;

优点
  1. 清楚地定义分层的复杂对象,表示对象的全部或部分层次。
  2. 让客户忽略层次的差异,方便对整个层次结构进行控制
  3. 简化客户端端代码
  4. 符合开闭原则
缺点
  1. 限制类型时比较复杂
  2. 使设计模式更加抽象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值