zoukankan      html  css  js  c++  java
  • 组合模式

      组合模式又叫合成模式,有时又叫整体-部分模式,主要用来描述整体和部分的关系,其定义为:将对象组合成树形结构以表示“整体-部分”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

      先说说组合模式的几个角色:

    • Component抽象构件角色:定义参加组合对象的共有方法和属性,也可以定义一些默认的行为或属性
    • Leaf叶子构件:叶子对象,其下再没有分支,也就是遍历的最小单位
    • Composite树枝构件:组合抽象构件和叶子构件形成一个树形结构

    下面看一个通用代码示例:

    //抽象构件
    public abstract class Component{
        //个体和整体都具有的共享
        public void doSomething(){
        }
    }
    //树枝构件,也是组合模式的重点
    public class Composite extends Component{
        //构件容器
        private ArrayList<Component> componentArrayList = new ArrayList();
        //增加一个叶子构件或树枝构件
        public void add(Component conponent){
            this.componentArrayList.add(conponent);
        }
        //删除一个叶子构件或树枝构件
        public void remove(Component conponent){
            this.componentArrayList.remove(conponent);
        }
        //获得分支下的所有叶子构件或树枝构件
        public ArrayList<Component> getChild(){
            return this.componentArrayList;
        }
    }
    //树叶构件
    public class Leaf extends Component{
        //可以选择性覆写父类方法
        public void doSomething(){
        }
    }
    //场景类
    public class Client{
        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);
        }
    }

    组合模式的优点:

    • 高层模块调用简单。一颗树形结构中的所有节点都是Component,局部和整体对调用者来说没有任何区别,也就是说,高层模块不必关心自己处理的是单个对象还是整个组合结构,简化了高层模块的代码。
    • 节点自由增加。使用了组合模式后,如果想增加一个树枝节点或叶子节点都是非常容易的,只要找到它的父节点就行,非常容易扩展。

    组合模式的缺点:

    • 树枝和叶子构件都直接使用了实现类,这在面向接口编程是不恰当的,也违背了依赖倒置原则。

    使用场景:

    • 维护部分-整体关系的场景,如树形菜单、文件和文件管理。
    • 从一个整体中能够独立出部分模块或功能的场景。

    注意事项:

      只要是树形结构,就要考虑使用组合模式,只要是体现局部和整体关系的时候,而且关系还比较深,就要考虑使用组合模式。

  • 相关阅读:
    记-码农的“启蒙”之《程序设计语言-实践之路》和《面向对象分析和设计》两书
    记-阅读以及书籍推荐(2014年9月7日更新)
    初探领域驱动设计(1)为复杂业务而生
    异步编程 In .NET
    Windows平台分布式架构实践
    Windows平台分布式架构实践
    一不小心写了个WEB服务器
    MVC5
    从Membership 到 .NET4.5 之 ASP.NET Identity
    bootstrap + requireJS+ director+ knockout + web API = 一个时髦的单页程序
  • 原文地址:https://www.cnblogs.com/loveBolin/p/9739263.html
Copyright © 2011-2022 走看看