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
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