• js设计模式(六)---组合模式


      组合模式将对象组合成树形结构,以表示“部分-整体”的层次结构。除了用来表示树形结构之外,组合模式的另一个好处是通过对象的多态性表现,使得用户对单个对象和组合对象的使用具有一致性。基本图例

     

    1、组合模式不是父子关系,

    2、组合模式对叶对象的操作一致

    3、双向映射关系。

    4、可以用职责链模式提高组合模式的性能

    //File 类的实现基本一致:
      var File = function( name ){
      this.name = name;
      this.parent = null;
    };
    File.prototype.add = function(){
      throw new Error( '不能添加在文件下面' );
    };
    File.prototype.scan = function(){
      console.log( '开始扫描文件: ' + this.name );
    };
    File.prototype.remove = function(){
      if ( !this.parent ){ //根节点或者树外的游离节点
        return;
      }
      for ( var files = this.parent.files, l = files.length - 1; l >=0; l-- ){
        var file = files[ l ];
        if ( file === this ){
          files.splice( l, 1 );
        }
      }
    };

    var folder = new Folder( '学习资料' );
    var folder1 = new Folder( 'JavaScript' );
    var file1 = new Folder ( '深入浅出 Node.js' );

    
    

    folder1.add( new File( 'JavaScript 设计模式与开发实践' ) );
    folder.add( folder1 );
    folder.add( file1 );
    folder1.remove(); //移除文件夹
    folder.scan();

    组合模式使用场景:

    1、表示对象的 “部分-整体“层次的结构

    2、客户希望统一对待树中的所有对象

  • 相关阅读:
    关于C语言中的绝对值函数
    B. Interesting drink(水题 二分)
    A. Boring Apartments(水题)
    A. FashionabLee(水题)
    A. Collecting Coins(水题)
    A. Fancy Fence(水题)
    最小公因数,最小公倍数,以及快速幂模板
    android:layout_gravity 和 android:gravity 的区别
    Android开发之Intent略解
    java中类的创建及初始化过程
  • 原文地址:https://www.cnblogs.com/web-Rain/p/7865237.html
Copyright © 2020-2023  润新知