組合模式 職責(zé)鏈模式
組合模式
組合模式將對(duì)象組合成樹形結(jié)構(gòu),以表示“部分-整體”的層次結(jié)構(gòu)。 在組合模式的樹形結(jié)構(gòu)中穴肘,所有的節(jié)點(diǎn)都類似于繼承了一個(gè)抽象類一樣,需要實(shí)現(xiàn)同樣名字的一個(gè)方法舔痕。
鑒于js沒有抽象類這玩意评抚;所以這個(gè)同名方法只能約定了。假如就約定為execute
好了伯复。
var BigCommand = function () {
this.commands = [];
}
BigCommand.prototype.add = function (command) {
this.commands.push(command);
}
BigCommand.prototype.execute = function () {
for (var i = 0; i < this.commands.lenth; i++) {
var command = this.commands[i];
command.execute();
}
}
var bigCommand = new BigCommand();
var Command = function () { }
Command.prototype.execute = function () {
throw new Error("需要實(shí)現(xiàn)execute方法")
}
上訴代碼慨代,我們可以通過BigCommand
生成一個(gè)組合對(duì)象,通過Command
生成一個(gè)小對(duì)象啸如。通過bigCommand.add(command)
侍匙,我們將葉子對(duì)象推入組合對(duì)象;組合對(duì)象也可以推入組合對(duì)象叮雳。這樣代碼就分離成幾個(gè)部分了想暗。
職責(zé)鏈模式
職責(zé)鏈模式:使多個(gè)對(duì)象都有機(jī)會(huì)處理請(qǐng)求,從而避免請(qǐng)求的發(fā)送者和接受者之間的耦合關(guān)系债鸡。
既然說是鏈了江滨,必然有鏈表的數(shù)據(jù)結(jié)構(gòu)在其中。鑒于js的異步特性厌均,并不適合用單純的一個(gè)指針來指著下一環(huán)唬滑;用cb()
是更好的選擇。
var Chain = function (fn) {
this.fn = fn
this.next = null;
}
Chain.prototype.setNext = function (fn) {
return this.next = fn;
}
Chain.prototype.execute = function () {
return this.fn.apply(this, arguments);
}
Chain.prototype.cb = function () {
return this.next && this.next.apply(this.next, arguments);
}
最后寫完發(fā)現(xiàn)職責(zé)鏈模式就是個(gè)流程控制嘛……還不如直接寫流程控制……