Let's start with the problem, where an order system is used:
In an e-commerce system, now we have the order module, and the information module two main modules, the next single success, we use to send order information to the customer.
Here is a simple workaround where we call the method of another class in one class.
//Order class, which stores all the variables and functions of the orderfunctionOrder (goods) { This. Goods =goods;} Order.prototype={done:function(){ //Order Completion Code This. sendsuccessmsg (); }, Sendsuccessmsg:function(){ varMessage =NewMessage (); Message.sendmsg ( This. Goods)}}//message class with various message function functionsfunctionMessage () {}message.prototype={sendmsg:function(Goods) {alert ("Product Name:" +goods.name+ "\ n" + "Price:" +Goods.price); } //methods of other information modules}varOrder =NewOrder ({name: "Sony headset", price:100}) Order.done ()//Pop-up product information
After a simple analysis of the code, we can find some problems, first of all, Order和Message紧耦合,一般来说,
when the modification of one class will require the modification of another class that is the coupling. Here, a straightforward question, when we change the name or parameter of the Sendmsg method in the message class, the corresponding function names and parameters in the order class are also modified.
Knowing the problem with this approach, let's look at how to improve this code with the Publish/subscribe pattern. Publish/subscribe mode is a kind of message communication mode, which is called by the publisher and the receiver of the information is called Subscribers.
Below is a simple system based on the Publish/subscribe model
varSubpub = {};(function(subpub) {varList = {}; Subpub.publish=function(topic,msg) { for(vari = 0; i<list[topic].length; i++) {List[topic][i] (msg); }} subpub.subscribe=function(topic,listener) {if(!list[topic]) list[topic] = []; List[topic].push (listener); }}) (Subpub)//TestSubpub.subscribe (' foo '),function(msg) {alert (msg);}); Subpub.publish (' foo ', ' Hello world! ')
This event management small system is applied to the previous order system for decoupling.
functionOrder (goods) { This. Goods =goods;} Order.prototype={done:function(){ //Order Completion Code This. sendsuccessmsg (); }, Sendsuccessmsg:function() {Subpub.publish (' Order/done ', This. Goods); }}functionMessage () {Subpub.subscribe (' Order/done ', This. sendmsg);} Message.prototype={sendmsg:function(Goods) {alert ("Product Name:" +goods.name+ "\ n" + "Price:" +Goods.price); } //methods of other information modules}varMessage =NewMessage ();varOrder =NewOrder ({name: "Sony headset", price:100}); Order.done ()//Pop-up product information
Now, we find that the message and order classes do not care about how each other is implemented. Modifying a function in a class does not consider whether it affects another class. However, it is important to save the event title.
JavaScript design mode--publish/subscribe