1. Definition
Chain of Responsibility Pattern: Give multiple objects the opportunity to process requests, thereby avoiding the coupling relationship between the sender and receiver of the request, connecting these objects into a chain, and along this The request is passed through the chain until an object handles it.
2. Example
/* 传统方式实现 */ // orderType:[1:500, 2:200, 3:普通],isPaid:true/false,stock:库存量 var order = function(orderType, isPaid, stock) { if(orderType === 1) { if(isPaid) { console.log("500元定金预购,得到100优惠券"); } else { if(stock > 0) { console.log("普通购买,无优惠券"); }else { console.log("库存不足"); } } }else if(orderType === 2) { if(isPaid) { console.log("200元定金预购,得到50优惠券"); } else { if(stock > 0) { console.log("普通购买,无优惠券"); }else { console.log("库存不足"); } } }else if(orderType === 2) { if(stock > 0) { console.log("普通购买,无优惠券"); }else { console.log("库存不足"); } } } order(1, true, 500); /*职责链 */ var order500 = function(orderType, isPaid, stock) { if(orderType === 1 && isPaid === true) { console.log("500元定金预购,得到100优惠券"); }else { return "nextSuccessor"; } }; var order200 = function(orderType, isPaid, stock) { if(orderType === 2 && isPaid === true) { console.log("200元定金预购,得到50优惠券"); }else { return "nextSuccessor"; } }; var orderNormal = function(orderType, isPaid, stock) { if(stock > 0) { console.log("普通购买,无优惠券"); }else { console.log("库存不足"); } }; Function.prototype.after = function(fn) { var self = this; return function() { var ret = self.apply(this, arguments); if(ret === "nextSuccessor") { return fn.apply(this, arguments); } return ret; }; } var order = order500.after(order200).after(orderNormal); order(1, true, 10);
Advantages: Decouples the complex relationship between the request sender and N recipients.
Disadvantages: There is no guarantee that a certain request will be processed by the nodes in the chain.
3. Example: File upload object
Example 2: Obtain file upload object using chain of responsibility model
PS: Compare "Learning JavaScript Design Patterns Iterator Pattern"
function getActiveUploadObj() { try{ return new ActiveObject("TXFTNActiveX.FTNUpload"); // IE上传控件 }catch(e) { return "nextSuccessor"; } } function getFlashUploadObj() { if(supportFlash().f === 1) { // supportFlash见《JavaScript设计模式--迭代器模式》 var str = '<object type="application/x-shockwave-flash"></object>'; return $(str).appendTo($("body")); } return "nextSuccessor"; } function getFormUploadObj() { var str = '<input name="file" type="file" class="ui-file" />'; return $(str).appendTo($("body")); } var getUploadObj = getActiveUploadObj.after(getFlashUploadObj).after(getFormUploadObj); console.log(getUploadObj());
Whether it is the scope chain, the prototype chain, or the event bubbling in the DOM node, we can find the shadow of the chain of responsibility.
The above is the entire content of this article. I hope this article will be helpful to everyone in learning javascript programming. .