组合模式

组合模式(Composite Pattern)也称为整体-部分(Part-Whole)模式,属于结构型模式。

它的宗旨是通过将单个对象(叶子节点)和组合对象(树枝节点)用相同的接口进行表示,使得客户端对单个对象和组合对象的使用具有一致性。

组合模式一般用来描述整体与部分的关系,它将对象组织到树形结构中,最顶层的节点称为根节点,根节点下面可以包含树枝节点和叶子节点,树枝节点下面又可以包含树枝节点和叶子节点。

应用场景

1.希望客户端可以忽略组合对象与单个对象的差异时。

2.对象层次具备整体和部分,呈树形结构。

例如:树形菜单,文件、文件夹的管理。

优缺点

优点:

1、高层模块调用简单。

2、节点自由增加。

缺点:

1.在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口,违反了依赖倒置原则。

主要角色

组合模式主要包含3个角色:

1.抽象根节点(Component)

定义系统各层次对象的共有方法和属性,可以预先定义一些默认行为和属性。

2.树枝节点(Composite)

定义树枝节点的行为,存储子节点,组合树枝节点和叶子节点形成一个树形结构。

3.叶子节点(Laf)

叶子节点对象,其下再无分支,是系统层次遍历的最小单位。

组合模式结构

分类

组合模式在具体实现上,有两种不同的方式,分别是透明组合模式和安全组合模式。

透明组合模式将公共接口封装到抽象根节点(Component)中,系统所有节点具备一致行为,如果当系统绝大多数层次具备相同的公共行为时,采用透明组合模式会更好。但是为剩下少数层次节点引入不需要的方法。

如果当系统各个层次差异性行为较多或者树节点层次相对稳定时,则采用安全组合模式。

透明组合模式

透明组合模式是把所有公共方法都定义在抽象根节点中,这样做的好处是客户端无需分辨是叶子节点(Leaf)和树枝节点(Composite),它们具备完全一致的接口。缺点是叶子节点(Leaf)会继承得到一些它所不需要(管理子类操作的方法)的方法,这与设计模式接口隔离原则相违背。

创建抽象根节点

把所有可能用到的方法都定义到这个最顶层的抽象类中,但是不写任何逻辑处理的代码,而是直接抛出异常。

禁止使用抽象方法,否则子类必须实现,于是体现不出各个子类的差异。子类只需要重写有差异的方法进行覆盖即可。

举例:分类目录为根节点,具体分类为树枝节点,分类下的商品为叶子节点。

public abstract class Component {
    public String getName(Component component) {
        throw new UnsupportedOperationException("getName is not supported");
    }
    public double getPrice(Component component) {
        throw new UnsupportedOperationException("getPrice is not supported");
    }
    public String print() {
        throw new UnsupportedOperationException("print is not supported");
    }
    public boolean addChild(Component component) {
        throw new UnsupportedOperationException("addChild is not supported");
    }
    public boolean removeChild(Component component) {
        throw new UnsupportedOperationException("removeChild is not supported");
    }
    public Component getChild(int index) {
        throw new UnsupportedOperationException("getChild is not supported");
    }
}

创建树枝节点

public class CompositeCategory extends Component {
    private String name;
    private List<Component> componentList = new ArrayList<Component>();
    public CompositeCategory(String name) {
        this.name = name;
    }
    @Override
    public String print() {
        StringBuilder builder = new StringBuilder(this.name);
        for (Component component : this.componentList) {
            if (component instanceof CompositeCategory) {
                builder.append("\n"   " -"   component.print());
            } else {
                builder.append("\n"   " --"   component.print());
            }
        }
        return builder.toString();
    }
    @Override
    public boolean addChild(Component component) {
        return this.componentList.add(component);
    }
    @Override
    public boolean removeChild(Component component) {
        return this.componentList.remove(component);
    }
    @Override
    public Component getChild(int index) {
        return this.componentList.get(index);
    }
}

创建叶子节点

public class CompositeProduct extends Component {
    private String name;
    private Double price;
    public CompositeProduct(String name, Double price) {
        this.name = name;
        this.price = price;
    }
    @Override
    public String print() {
        return this.name   " (¥"   this.price   "元)";
    }
    @Override
    public String getName(Component component) {
        return this.name;
    }
    @Override
    public double getPrice(Component component) {
        return this.price;
    }
}

客户端调用

  public static void main(String[] args) {
        // 根节点
        Component root = new CompositeCategory("分类目录");
        // 树枝节点
        Component categoryA = new CompositeCategory("分类A");
        Component categoryB = new CompositeCategory("分类B");
        // 叶子节点
        Component productA = new CompositeProduct("productA ", 20.5);
        Component productB = new CompositeProduct("productB ", 30.5);
        Component productC = new CompositeProduct("productC", 25.5);
        root.addChild(categoryA);
        categoryA.addChild(productA);
        root.addChild(categoryB);
        categoryB.addChild(productB);
        categoryB.addChild(productC);
        System.out.println(root.print());
        System.out.println("-----------------------");
        Component child = root.getChild(1);
        System.out.println(child.print());
        System.out.println("-----------------------");
        root.removeChild(categoryA);
        System.out.println(root.print());
    }

分类目录
-分类A
--productA (¥20.5元)
-分类B
--productB (¥30.5元)
--productC (¥25.5元)
-----------------------
分类B
--productB (¥30.5元)
--productC (¥25.5元)
-----------------------
分类目录
-分类B
--productB (¥30.5元)
--productC (¥25.5元)

安全组合模式

安全组合模式是只规定系统各个层次的最基础的一致行为,而把组合(树节点)本身的方法(管理子类对象的添加,删除等)放到自身当中。

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

创建抽象根节点

public abstract class Component {
    protected String name;
    public Component(String name) {
        this.name = name;
    }
    public abstract String print();
}

创建树枝节点

public class CompositeCategory extends Component {
    private List<Component> componentList;
    public CompositeCategory(String name) {
        super(name);
        this.componentList = new ArrayList<Component>();
    }
    @Override
    public String print() {
        StringBuilder builder = new StringBuilder(this.name);
        for (Component component : this.componentList) {
            if (component instanceof CompositeCategory) {
                builder.append("\n"   " -"   component.print());
            } else {
                builder.append("\n"   " --"   component.print());
            }
        }
        return builder.toString();
    }
    public boolean addChild(Component component) {
        return this.componentList.add(component);
    }
    public boolean removeChild(Component component) {
        return this.componentList.remove(component);
    }
    public Component getChild(int index) {
        return this.componentList.get(index);
    }
}

创建叶子节点

public class CompositeProduct extends Component {
    private Double price;
    public CompositeProduct(String name, Double price) {
        super(name);
        this.price = price;
    }
    @Override
    public String print() {
        return this.name   " (¥"   this.price   "元)";
    }
    public String getName() {
        return this.name;
    }
    public double getPrice() {
        return this.price;
    }
}

客户端调用

    public static void main(String[] args) {
        // 根节点
        CompositeCategory root = new CompositeCategory("分类目录");
        // 树枝节点
        CompositeCategory categoryA = new CompositeCategory("分类A");
        CompositeCategory categoryB = new CompositeCategory("分类B");
        // 叶子节点
        CompositeProduct productA = new CompositeProduct("productA", 20.5);
        CompositeProduct productB = new CompositeProduct("productB", 30.5);
        CompositeProduct productC = new CompositeProduct("productC", 25.5);
        root.addChild(categoryA);
        categoryA.addChild(productA);
        root.addChild(categoryB);
        categoryB.addChild(productB);
        categoryB.addChild(productC);
        System.out.println(root.print());
        System.out.println("-----------------------");
        Component child = root.getChild(1);
        System.out.println(child.print());
        System.out.println("-----------------------");
        root.removeChild(categoryA);
        System.out.println(root.print());
    }

分类目录
-分类A
--productA (¥20.5元)
-分类B
--productB (¥30.5元)
--productC (¥25.5元)
-----------------------
分类B
--productB (¥30.5元)
--productC (¥25.5元)
-----------------------
分类目录
-分类B
--productB (¥30.5元)
--productC (¥25.5元)

到此这篇关于Java结构型设计模式之组合模式详解的文章就介绍到这了,更多相关Java组合模式内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Java结构型设计模式之组合模式详解的更多相关文章

  1. Swift设计模式之组合模式

    转自Swift设计模式原文Design-Patterns-In-Swift

  2. MVVM 不是那么好

    我觉得MVVM是一种反人类的设计模式,它使架构更加混乱而非清晰。MVVM命名很糟糕名称是很重要的。ViewModel这一名称则没有发挥任何作用。ViewModel的第一种含义是modelfortheview。MVVM引进太多职责命名不够具体,导致这个类的任务无休止地增长。MVVM不改变你的架构viewmodel并不能从根本上改变你的应用程序的架构。我能想到的MVVM模式最大的好处就是它把“下水道”从苹果自带的viewcontrooller类转移到了viewmodel这一自定义的对象。

  3. 开发Swift iOS应用程序“正确的方式”

    最近,我学习了Swift和开发iOS应用程序的基础知识。现在,我想自己开发一个真正的应用程序,但我非常关心编写好的代码,所以我已经寻找“最佳实践”,“设计模式”和“正确的方式”来实现它。在我的搜索中,我发现这个greattutorial关于SwiftiOS应用程序中通常使用的所有设计模式,以及他们使用的示例。不应该将httpClient和persistencyManager声明为协议,然后HttpClient和PersistencyManager类实现该协议?我应该在哪里告诉应用程序?最后但并非最不重要的

  4. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. javascript的23种设计模式示例总结大全

    这篇文章主要为大家介绍了javascript的23种设计模式的总结大全,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  6. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 详解JavaScript实现设计模式中的适配器模式的方法

    适配器模式可以根据需求转换(或调整)一个接口,创建含有您所需接口的另一个对象,并将它连接到您想改变接口的对象,从而完成这种转换,下面就来详解JavaScript实现设计模式中的适配器模式的方法

  9. Java实现世界上最快的排序算法Timsort的示例代码

    Timsort 是一个混合、稳定的排序算法,简单来说就是归并排序和二分插入排序算法的混合体,号称世界上最好的排序算法。本文将详解Timsort算法是定义与实现,需要的可以参考一下

  10. PHP设计模式之工厂模式详解

    这篇文章主要为大家详细介绍了PHP设计模式之工厂模式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部