本文爲閱讀《Javascript設計模式》一書後,總結部分內容而得。其內部的代碼和截圖都來源自該書。
使用組合模式的一個場景示例
想象一下,現在你需要維護一個個人信息的頁面,當用戶不同時,頁面也可能會發生變化。比如,當用戶爲小明時,展示給他的頁面是這樣的
而當用戶爲小紅時,展示給她的頁面是這樣的
我現在想要實現保存頁面信息的功能,面對各種各樣的可能頁面,頁面上的各種元素保存信息的方式也不同,比如select和input框,其取值方式就完全不同。我要如何通過統一的函數來保存這些頁面信息呢?有一種方法,是通過每次保存頁面時,都遍歷頁面所有元素,判斷所有元素類型,並依據個元素類型執行對應的save函數。但這樣很顯然,會使代碼看上去混亂且臃腫。
用組合模式實現保存功能則你可以用一條簡單的命令,在多個子對象上激發遞歸行爲,將保存功能委託給各個子對象來實現,讓每個子對象都知道如何保存自己本身的信息,父對象只是起到一個傳遞調用的功能。
組合模式
組合對象的結構
什麼情況下使用組合模式
- 存在一批組織成某種層次體系的對象
- 希望對這批對象或其中一部分對象實施一個操作
一個使用組合模式的示例----表單信息存儲
明確組合對象及葉對象要具備的函數
var Composite=new Interface('Composite',['add''remove','getChild']);
var FormItem=new Interface('FormItem',['save']);
定義葉對象
var Field = function(id) { // implements Composite, FormItem
this.id = id;
this.element;
};
Field.prototype.add = function() {};
Field.prototype.remove = function() {};
Field.prototype.getChild = function() {};
Field.prototype.save = function() {
setCookie(this.id, this.getValue);
};
Field.prototype.getElement = function() {
return this.element;
};
Field.prototype.getValue = function() {
throw new Error('Unsupported operation on the class Field.');
};
父類定義好後,我們來定義各個葉對象。在這個應用中,我們假定頁面是由input框、select框以及textarea組成,那麼我們來定義這三個葉對象。/* InputField class. */
var InputField = function(id, label) { // implements Composite, FormItem
Field.call(this, id);
this.input = document.createElement('input');
this.input.id = id;
this.label = document.createElement('label');
var labelTextNode = document.createTextNode(label);
this.label.appendChild(labelTextNode);
this.element = document.createElement('div');
this.element.className = 'input-field';
this.element.appendChild(this.label);
this.element.appendChild(this.input);
};
extend(InputField, Field); // Inherit from Field.
InputField.prototype.getValue = function() {
return this.input.value;
};
/* TextareaField class. */
var TextareaField = function(id, label) { // implements Composite, FormItem
Field.call(this, id);
this.textarea = document.createElement('textarea');
this.textarea.id = id;
this.label = document.createElement('label');
var labelTextNode = document.createTextNode(label);
this.label.appendChild(labelTextNode);
this.element = document.createElement('div');
this.element.className = 'input-field';
this.element.appendChild(this.label);
this.element.appendChild(this.textarea);
};
extend(TextareaField, Field); // Inherit from Field.
TextareaField.prototype.getValue = function() {
return this.textarea.value;
};
/* SelectField class. */
var SelectField = function(id, label) { // implements Composite, FormItem
Field.call(this, id);
this.select = document.createElement('select');
this.select.id = id;
this.label = document.createElement('label');
var labelTextNode = document.createTextNode(label);
this.label.appendChild(labelTextNode);
this.element = document.createElement('div');
this.element.className = 'input-field';
this.element.appendChild(this.label);
this.element.appendChild(this.select);
};
extend(SelectField, Field); // Inherit from Field.
SelectField.prototype.getValue = function() {
return this.select.options[this.select.selectedIndex].value;
};
定義根級組合對象
</pre><pre name="code" class="javascript">var CompositeForm = function(id, method, action) { // implements Composite, FormItem
this.formComponents = [];
this.element = document.createElement('form');
this.element.id = id;
this.element.method = method || 'POST';
this.element.action = action || '#';
};
CompositeForm.prototype.add = function(child) {
Interface.ensureImplements(child, Composite, FormItem);
this.formComponents.push(child);
this.element.appendChild(child.getElement());
};
CompositeForm.prototype.remove = function(child) {
for(var i = 0, len = this.formComponents.length; i < len; i++) {
if(this.formComponents[i] === child) {
this.formComponents.splice(i, 1); // Remove one element from the array at
// position i.
break;
}
}
};
CompositeForm.prototype.getChild = function(i) {
return this.formComponents[i];
};
CompositeForm.prototype.save = function() {
for(var i = 0, len = this.formComponents.length; i < len; i++) {
this.formComponents[i].save();
}
};
CompositeForm.prototype.getElement = function() {
return this.element;
};
組合對象和葉對象的匯合
var contactForm = new CompositeForm('contact-form', 'POST', 'contact.php');
contactForm.add(new InputField('first-name', 'First Name'));
contactForm.add(new InputField('last-name', 'Last Name'));
contactForm.add(new InputField('address', 'Address'));
contactForm.add(new InputField('city', 'City'));
contactForm.add(new SelectField('state', 'State', stateArray)); // var stateArray =
[{'al', 'Alabama'}, ...]
contactForm.add(new InputField('zip', 'Zip'));
contactForm.add(new TextareaField('comments', 'Comments'));
addEvent(window, 'unload', contactForm.save);
總結下通過該模式實現保存功能的流程,首先,我們對頁面添加了監聽,一旦頁面加載,就調用組合對象的save方法,而該save函數,遍歷了其下的所有葉對象,並調用該對象的save函數來實現其save函數。
向接口添加方法
//修改接口的定義
var FormItem = new Interface('FormItem', ['save', 'restore']);
//爲各個葉對象、組合對象添加對應的函數
Field.prototype.restore = function() {
this.element.value = getCookie(this.id);
};
CompositeForm.prototype.restore = function() {
for(var i = 0, len = this.formComponents.length; i < len; i++) {
this.formComponents[i].restore();
}
};
//添加觸發函數實現功能
addEvent(window, 'load', contactForm.restore);
更復雜一點的示例
好,第一個示例我們已經實現了,更進一步,如果現在我想對某幾個葉對象的組合執行某些操作呢?比如說, 我想在一定條件被觸發時,對某幾個葉對象執行save函數,而不是對所有葉對象執行該函數。這時,我們就需要添加非根級的組合對象了,也就是說,把這幾個想要操作的葉對象,視爲一個組合對象。
定義非根級組合對象
var CompositeFieldset = function(id, legendText) { // implements Composite, FormItem
this.components = {};
this.element = document.createElement('fieldset');
this.element.id = id;
if(legendText) { // Create a legend if the optional second
// argument is set.
this.legend = document.createElement('legend');
this.legend.appendChild(document.createTextNode(legendText);
this.element.appendChild(this.legend);
}
};
CompositeFieldset.prototype.add = function(child) {
Interface.ensureImplements(child, Composite, FormItem);
this.components[child.getElement().id] = child;
this.element.appendChild(child.getElement());
};
CompositeFieldset.prototype.remove = function(child) {
delete this.components[child.getElement().id];
};
CompositeFieldset.prototype.getChild = function(id) {
if(this.components[id] != undefined) {
return this.components[id];
}
else {
return null;
}
};
CompositeFieldset.prototype.save = function() {
for(var id in this.components) {
if(!this.components.hasOwnProperty(id)) continue;
this.components[id].save();
}
};
CompositeFieldset.prototype.restore = function() {
for(var id in this.components) {
if(!this.components.hasOwnProperty(id)) continue;
this.components[id].restore();
}
};
CompositeFieldset.prototype.getElement = function() {
return this.element;
};
組合對象和葉對象匯合
var contactForm = new CompositeForm('contact-form', 'POST', 'contact.php');
//一個組合對象
var nameFieldset = new CompositeFieldset('name-fieldset');
nameFieldset.add(new InputField('first-name', 'First Name'));
nameFieldset.add(new InputField('last-name', 'Last Name'));
contactForm.add(nameFieldset);
//又一個組合對象
var addressFieldset = new CompositeFieldset('address-fieldset');
addressFieldset.add(new InputField('address', 'Address'));
addressFieldset.add(new InputField('city', 'City'));
addressFieldset.add(new SelectField('state', 'State', stateArray));
addressFieldset.add(new InputField('zip', 'Zip'));
contactForm.add(addressFieldset);
contactForm.add(new TextareaField('comments', 'Comments'));
body.appendChild(contactForm.getElement());
addEvent(window, 'unload', contactForm.save);
addEvent(window, 'load', contactForm.restore);
//對指定組合對象的操作
addEvent('save-button', 'click', nameFieldset.save);
addEvent('restore-button', 'click', nameFieldset.restore);