從生活中的例子可以發(fā)現(xiàn),某個(gè)請(qǐng)求可能需要幾個(gè)人的審批,即使技術(shù)經(jīng)理審批完了,還需要上一級(jí)的審批。這樣的例子,還有公司中的請(qǐng)假,少于3天的,直屬Leader就可以批準(zhǔn),3天到7天之內(nèi)就需要項(xiàng)目經(jīng)理批準(zhǔn),多余7天的就需要技術(shù)總監(jiān)的批準(zhǔn)了。介紹了這么多生活中責(zé)任鏈模式的例子的,下面具體給出面向?qū)ο笾胸?zé)任鏈模式的定義。
責(zé)任鏈模式涉及的對(duì)象只有處理者角色,但由于有多個(gè)處理者,它們具有共同的處理請(qǐng)求的方法,所以這里抽象出一個(gè)抽象處理者角色進(jìn)行代碼復(fù)用.
實(shí)現(xiàn)
請(qǐng)求類
// 采購(gòu)請(qǐng)求 let PurchaseRequest = function (amount, productName) { this.amount = amount; this.productName = productName; };
處理者接口類
// 審批人,Handler let Approver = function (name, nextApprover) { this.name = name; this.nextApprover = nextApprover; }; Approver.prototype.processRequest = function () { throw new Error(); };
處理者類
// ConcreteHandler let Manager = function (name, nextApprover) { Approver.call(this, name, nextApprover); }; extend(Manager, Approver); Manager.prototype.processRequest = function (request) { if (request.Amount < 10000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request); } }; // ConcreteHandler,副總 let VicePresident = function (name, nextApprover) { Approver.call(this, name, nextApprover); }; extend(VicePresident, Approver); VicePresident.prototype.processRequest = function (request) { if (request.Amount < 25000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request); } }; // ConcreteHandler,總經(jīng)理 let President = function (name, nextApprover) { Approver.call(this, name, nextApprover); }; extend(President, Approver); President.prototype.processRequest = function (request) { if (request.Amount < 100000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request); } };
測(cè)試
let requestTelphone = new PurchaseRequest(4000.0, "Telphone"); let requestSoftware = new PurchaseRequest(10000.0, "Visual Studio"); let requestComputers = new PurchaseRequest(40000.0, "Computers"); let manager = new Manager("LearningHard"); let Vp = new VicePresident("Tony"); let Pre = new President("BossTom"); // 設(shè)置責(zé)任鏈 manager.NextApprover = Vp; Vp.NextApprover = Pre; // 處理請(qǐng)求 manager.ProcessRequest(requestTelphone); manager.ProcessRequest(requestSoftware); manager.ProcessRequest(requestComputers);
使用場(chǎng)景
一個(gè)系統(tǒng)的審批需要多個(gè)對(duì)象才能完成處理的情況下,例如請(qǐng)假系統(tǒng)等。
代碼中存在多個(gè)if-else語(yǔ)句的情況下,此時(shí)可以考慮使用責(zé)任鏈模式來(lái)對(duì)代碼進(jìn)行重構(gòu)。
特點(diǎn)
降低了請(qǐng)求的發(fā)送者和接收者之間的耦合。
把多個(gè)條件判定分散到各個(gè)處理類中,使得代碼更加清晰,責(zé)任更加明確。
責(zé)任鏈模式也具有一定的缺點(diǎn),如:
在找到正確的處理對(duì)象之前,所有的條件判定都要執(zhí)行一遍,當(dāng)責(zé)任鏈過(guò)長(zhǎng)時(shí),可能會(huì)引起性能的問(wèn)題, 可能導(dǎo)致某個(gè)請(qǐng)求不被處理。
總結(jié)
責(zé)任鏈降低了請(qǐng)求端和接收端之間的耦合,使多個(gè)對(duì)象都有機(jī)會(huì)處理某個(gè)請(qǐng)求。使得責(zé)任分割, 更具體, 有助于拓展
相關(guān)推薦:
Javascript責(zé)任鏈模式介紹
Java設(shè)計(jì)模式中責(zé)任鏈模式的實(shí)例分析
常用設(shè)計(jì)模式之責(zé)任鏈模式及其php實(shí)現(xiàn)
以上就是js責(zé)任鏈模式詳解的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!