The Combination Model of Learning Notes in javascript Design Patterns

Keywords: Javascript

Combination mode

  • Combination pattern is to combine objects into a tree structure to represent the "part-whole" hierarchical structure. Furthermore, it uses the polymorphism of objects to treat the combination objects and individual objects in a unified way.
  • Note:

    • Combination patterns are not paternity
    • Consistency of Leaf Object Operations
    • Bidirectional mapping relationship
    • Improving the Performance of Composite Patterns by Using Responsibility Chain Patterns
  • Application scenario

    • Part-Whole Hierarchy Representing Objects
    • Customers want to treat all objects in the tree uniformly
  • Examples: Scanning folders

    /* * * * * * Folder****** */
    var Folder = function(name) {
        this.name = name;
        this.files = [];
        this.parent = null;
    }
    
    Folder.prototype.add = function(file) {
        file.parent = this;
        this.files.push(file);
    }
    
    Folder.prototype.scan = function() {
        console.log('Start scanning folders:' + this.name);
        var i = 0,
            len = this.files.length,
            file;
        
        for(; i < len; i++) {
            file = this.files[i];
            file.scan();
        }
    }
    
    Folder.prototype.remove = function() {
        if (!this.parent) {
            return;
        }
        var i = this.parent.files.length - 1,
            files = this.parent.files,
            file;
    
        for(; i >= 0; i--) {
            file = files[i];
            if (file === this) {
                files.splice(i, 1);
            }
        }
    }
    
    /* * * * * * File****** */
    var File = function(name) {
        this.name = name;
        this.parent = null;
    }
    
    File.prototype.add = function() {
        throw new Error('No more files can be added under the file');
    }
    
    File.prototype.scan = function() {
        console.log('Start scanning files:' + this.name);
    }
    
    File.prototype.remove = function() {
        if (!this.parent) {
            return;
        }
        var i = this.parent.files.length - 1,
            files = this.parent.files,
            file;
    
        for(; i >= 0; i--) {
            file = files[i];
            if (file === this) {
                files.splice(i, 1);
            }
        }
    }

Posted by shivani.shm on Wed, 02 Oct 2019 09:09:58 -0700