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