[設計模式][組合模式][Javascript]

The Composite Pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets client treat individual objects and compositions uniformly.
From http://en.wikipedia.org/wiki/Composite_patternjavascript

定義

組合模式的目標是解耦客戶程序與複雜元素內部架構,使得客戶程序對待全部子元素都一視同仁html

每一個子節點均可以使複雜的存在,對於父節點來講,不須要知道子節點的複雜性或者實現子節點的複雜性,只須要關注子節點的特定方法,即可以使用子節點。簡化了父和子之間的關係。java

對於子節點來講也是同樣的,過多的接口暴露有時候也是一種濫用,同時也減小了對外部的依賴。node

需求

請輸入圖片描述

按鈕組需求:git

  • 有這樣一組按鈕,他們橫向的進行排列,根據當前用戶權限設置有哪些按鈕被顯示
  • 按鈕能夠分紅subgroup,按特定的功能進行劃分subgroup

類圖

請輸入圖片描述

角色

  • AbstractButton (Component) 定義一組公共的接口
  • Button (Leaf) 表示葉子節點的對象,葉子節點沒有本身的子節點
  • ButtonGroup (Composite) 定義有枝節點行爲,用來存儲子部件,在Component接口中實現與子部件有關操做

實現

var prototype = require('prototype');

var AbstractButton = prototype.Class.create({
  render: function() {
    throw new Error('method must be override!');
  }
});

var Button = prototype.Class.create(AbstractButton, {
  initialize: function(id, group) {
    this.id = id;
    this.group = group;
  },

  render: function () {
    console.log('render: Button的ID是:'+this.id+', group是:'+this.group);
  }
});

var ButtonGroup = prototype.Class.create(AbstractButton, {
  initialize: function () {
    this.buttons = [];
  },

  add: function (btn) {
    if (btn instanceof Button) {
      this.buttons.push(btn);
    }
  },

  remove: function (id) {
    for (var i = this.buttons.length - 1; i >= 0; i--) {
      if(this.buttons[i].id === id){
        this.buttons.splice(i, 1);
      }
    }
  },

  getChild: function (id) {
    var search = [];
    for (var i = this.buttons.length - 1; i >= 0; i--) {
      if(this.buttons[i].id === id){
        search.push(this.buttons[i]);
      }
    }

    return search;
  },

  render: function () {
    for (var i = this.buttons.length - 1; i >= 0; i--) {
      this.buttons[i].render();
    }
  }
});

var Main = function () {

  var editBtn = new Button('editbtn', 'edit');
  var deleteBtn = new Button('deletebtn', 'edit');
  var manageBtn = new Button('managebtn', 'edit');

  var btngroup = new ButtonGroup();
  btngroup.add(editBtn);
  btngroup.add(deleteBtn);
  btngroup.add(manageBtn);


  btngroup.render();
}

Main();

注:繼承採用了PrototypeJS提供的Class來作的,使用了Prototype.Node,關於prototype如何使用參考Prototype Docgithub

參考

相關文章
相關標籤/搜索