Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write the code of javascript responsibility chain mode

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article "javascript chain of responsibility mode code how to write" most people do not understand, so the editor summarized the following content, detailed, clear steps, with a certain reference value, I hope you can get something after reading this article, let's take a look at this "javascript chain of responsibility mode code how to write" article.

Definition of the chain of responsibility: make multiple objects have the opportunity to process the request, thus avoiding the coupling between the sender and receiver of the request, connect these objects into a chain, and pass the request along the chain. until an object can handle it, these objects in the delivery chain are called nodes.

Demand background: an e-commerce website, when users pay 500 deposit and deposit has been paid, they can enjoy 500 coupons and are not limited by the quantity of goods; when users pay 200 deposit and deposit has been paid, they can enjoy 500 coupons and are not limited by the quantity of goods; users are limited by the quantity of goods when they do not pay a deposit, buy at the original price when they are available, but cannot buy when they are out of stock.

The original version, if else judges all the way.

Var buyOrder = function (orederType, pay, stock) {if (orederType = = 1) {if (pay) {console.log ('500Voucher');} else {if (stock > 0) {console.log ('regular shopping page');} else {console.log ('out of stock') } else if (orederType = = 2) {if (pay) {console.log ('200coupon');} else {if (stock > 0) {console.log ('regular shopping page');} else {console.log ('out of stock') } else if (orederType = = 3) {if (stock > 0) {console.log ('general shopping page');} else {console.log ('out of stock');} buyOrder (1, true, 600)

Improved version

Var order500 = function (orderType, pay, stock) {if (orderType = ='1' & & pay = = true) {console.log ('500coupon');} else {order200 (orderType, pay, stock)} var order200 = function (orderType, pay, stock) {if (orderType = ='2' & & pay = = true) {console.log ('200coupon') } else {orderNormal (orderType, pay, stock)} var orderNormal = function (orderType, pay, stock) {if (stock > 0) {console.log ('regular shopping page');} else {console.log ('out of stock');} order500 (3, true, 0)

Optimized version 1:

Synchronous chain of responsibilities

/ 3 order functions, all of which are node functions var order500 = function (orderType, pay, stock) {if (orderType = ='1' & & pay = = true) {console.log ('500 coupons');} else {return 'nextSuccessor' / / I don't know who the next node is, but pass the request back}} var order200 = function (orderType, pay, stock) {if (orderType = ='2' & & pay = = true) {console.log ('200coupon');} else {return 'nextSuccessor' / / I don't know who the next node is, but pass the request back}} var orderNormal = function (orderType, pay, stock) {if (stock > 0) {console.log ('ordinary shopping page');} else {console.log ('out of stock');} / / responsibility constructor var Chain = function (fn) {this.fn = fn; this.successor = null } Chain.prototype.setNextSuccessor = function (successor) {/ / set the order of responsibilities method this.successor = successor} Chain.prototype.passRequest = function () {/ / request delivery var ret = this.fn.apply (this, arguments) if (ret = 'nextSuccessor') {return this.successor & & this.successor.passRequest.apply (this.successor, arguments)} return ret } / / package the three order functions as nodes of the responsibility chain var chainOrder500 = new Chain (order500) var chainOrder200 = new Chain (order200) var chainOrderNormal = new Chain (orderNormal) / / then specify the order of the nodes in the responsibility chain chainOrder500.setNextSuccessor (chainOrder200) chainOrder200.setNextSuccessor (chainOrderNormal) / / and finally pass the request to the first node Open the chain of responsibility mode to deliver chainOrder500.passRequest (1, true, 500) / / 500 coupons chainOrder500.passRequest (3, true, 20) / / General shopping page chainOrder500.passRequest (3, true, 0) / / out of stock / / if there is a demand change in the middle at this time, just do this: var order300 = function () {if (orderType = ='3' & & pay = = true) {console.log ('300 coupons') } else {return 'nextSuccessor' / / I don't know who the next node is, but pass the request back}} var chainOrder300 = new Chain (order300) / / add a new responsibility node chainOrder500.setNextSuccessor (chainOrder300) chainOrder300.setNextSuccessor (chainOrder300) / / modify the order chain order chainOrder200.setNextSuccessor (chainOrderNormal) / / so that you can completely ignore the original order function code and just add a node. Then reset the order of the relevant nodes in the chain of responsibilities.

Optimized version 2: asynchronous chain of responsibilities

In actual development, we often encounter some asynchronous problems, such as initiating an ajax request in the node function, and the result returned by the asynchronous request can determine whether to continue the passRequest in the on-the-job responsibility chain.

You can add another prototype method to the Chain class:

/ / responsibility constructor var Chain = function (fn) {this.fn = fn; this.successor = null } Chain.prototype.setNextSuccessor = function (successor) {/ / set the order of responsibilities method this.successor = successor} Chain.prototype.passRequest = function () {/ / request delivery var ret = this.fn.apply (this, arguments) if (ret = 'nextSuccessor') {/ / to the next node in the chain of responsibilities return this.successor & this.successor.passRequest.apply (this.successor, arguments)} return ret } / / added, which means manually passing the request to the next node in the responsibility chain Chain.prototype.next = function () {return this.successor & & this.successor.passRequest.apply (this.successor, arguments)} / / Asynchronous responsibility chain example var fn1 = new Chain (function () {console.log (1); return 'nextSuccessor'}) var fn2 = new Chain (function () {console.log (2); var self = this) SetTimeout (function () {self.next ()}, 1000)}) var fn3 = new Chain (function () {console.log (3);}) / / specify the sequence of nodes in the responsibility chain fn1.setNextSuccessor (fn2) fn2.setNextSuccessor (fn3) / / pass the request to the first node, and start the node passing fn1.passRequest () / / output 12. (1 second later). This is an asynchronous chain of responsibilities in which the request is passed in the chain of responsibility node, but the node has the right to decide when to hand the request to the next node. This creates an asynchronous ajax queue library.

Tips:

Here is an additional point of knowledge: "short circuit evaluation" & & will return the first false value (0, null, "", undefined, NaN), while | | will return the first true value.

Var x = a | | b | | c is equivalent to:

Var x X if (a) {x = a;} else if (b) {x = b;} else {x = c;}

Var x = a & b & c is equivalent to:

Var x = a Ting if (a) {x = b; if (b) {x = c;}}

So & & is sometimes used instead of if (expression) doSomething (), and the way to turn it into & & is expression & & doSomething ().

And | | compare is used to set the default value in the function, such as:

Function doSomething (arg1, arg2, arg3) {arg1 = arg1 | | 'arg1Value'; arg2 = arg2 | |' arg2Value';}

However, you also need to look at the specific usage scenarios. For example, if the arg1 passed in by doSomething () is required to be a numeric value, there will be a problem with the above writing (the default value is considered a false value when 0 is passed in).

Nowadays, the more common methods used by individuals are only to judge whether they are equal to undefined, such as

Function doSomething (arg) {arg = arg! = = void 0? Arg: 0;}

The advantage of the chain of responsibility model: decouple the complex relationship between the request sender and N receivers, and since you don't know which node in the chain can handle your request, you just need to pass the request to the first node.

If in actual development, you can use the responsibility chain pattern when maintaining a large function with multiple conditional branch statements. The node objects in the chain can be split and reorganized flexibly, adding and deleting nodes, and there is no need to change the code in other node functions.

The above is the content of this article on "how to write the code of the javascript chain of responsibility mode". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report