Depth analysis and implementation of LazyMan

I, entitled Introduction

Here is what I copy from the online face of the original questions:

Achieve a LazyMan, can be invoked as follows:
LazyMan ( "Hank") Output:
!! Hi This IS Hank

LazyMan ( "Hank") SLEEP (10) .eat ( "Dinner") output.
Hi This IS Hank!!
/ / wait 10 seconds ..
the Wake up After 10
Eat. Dinner ~

LazyMan ( "Hank &"). EAT ( "Dinner"). EAT ( "Supper") outputs
the Hi This IS Hank &!
Eat. Dinner ~
Eat. Supper ~

LazyMan ( "Hank &" ) .sleepFirst (5) .eat ( " supper") output
// wait for 5 seconds
the Wake up the After 5
Hi This IS Hank!
Eat. Supper

and so on.

Second, the study of the subject point

First statement: I am not a micro-channel staff to study the point is I guess is probably not, ha ha!

1. Method chained calls
 using 2 classes and object-oriented programming ideas
 3. Design patterns
 decouple code 4.
 5. minimum knowledge principle, i.e. Demeter (Law of Demeter)
 6. The code writing structure and naming

Third, analytical thinking title

1. Look at the title example of the output, you can determine which is the personification of the output, that is to say: should write a class to define a class of people called LazyMan. Can output name, eating, sleeping and other behavior.
 2. As can be seen from the sentence output priority sleepFrist is the highest priority consistent with other actions.
 3. Three examples from the point of view, had to first call LazyMan to initialize a person to continue the follow-up behavior, so LazyMan is an interface.
 4. The order of execution of the sentence is the order of the calling method, it is a queue.

Fourth, the use of the observer pattern implementation code

4.1 modular coding mode

(function(window, undefined){ })(window); 

4.2 declare a variable taskList, you need to queue to store information

(function(window, undefined){ var taskList = []; })(window); 

Queue, for storing a design of the individual items JSON, message store to be triggered, and a list of parameters required for performing the methods. For example LazyMan ( 'Hank'), the stored information as needed.

{
    'msg':'LazyMan', 'args':'Hank' } 

When the execution LazyMan method, call the subscription method, the information will need to perform into taskList in cached.
 Information stored can be kept up with, and other published methods of extraction, execution and output.

4.3 subscription method

Called subscription method of design:subscribe("lazyMan", "Hank")

(function(window, undefined){ var taskList = []; // 订阅 function subscribe(){ var param = {}, args = Array.prototype.slice.call(arguments); if(args.length < 1){ throw new Error("subscribe 参数不能为空!"); } param.msg = args[0]; // 消息名 param.args = args.slice(1); // 参数列表 if(param.msg == "sleepFirst"){ taskList.unshift(param); }else{ taskList.push(param); } } })(window); 

With a param variable to organize the information that you need to store, and then push into the taskList in cached.
 In particular, if sleepFirst, are placed in the head of the queue.

4.4 release method

(function(window, undefined){ var taskList = []; // 订阅方法 代码... // 发布 function publish(){ if(taskList.length > 0){ run(taskList.shift()); } } })(window); 

The store queue is read out, to run method (暂定,后续实现)to perform. Each release is defined herein perform only one, in order to maintain the queue one by one inside the method may be performed.
 Another reason, as used herein, shift () method is the removal of one, in this deleted queue, to avoid repeated.

4.5 achieve LazyMan class

// 类
function LazyMan(){}; LazyMan.prototype.eat = function(str){ subscribe("eat", str); return this; }; LazyMan.prototype.sleep = function(num){ subscribe("sleep", num); return this; }; LazyMan.prototype.sleepFirst = function(num){ subscribe("sleepFirst", num); return this; }; 

The LazyMan class implementation, has eat, sleep, sleepFrist other acts.
 Trigger a behavior, it is recorded once in taskList and returns the current object to support chained calls.

4.6 packaging methods to achieve the output console.log

// 输出文字
function lazyManLog(str){ console.log(str); } 

Why is console.log packaging layer, because in the real items, the Sankei often prompted to modify the output of UI. If everywhere are called directly with console.log, then change up a lot of trouble.
 In addition, if you want to lower version compatible with IE and other browsers, you can easily modify.
 That is the DRY principle (Do not Repeat Youself).

4.7 Specific methods to achieve the implementation of

// 具体方法
function lazyMan(str){ lazyManLog("Hi!This is "+ str +"!"); publish(); } function eat(str){ lazyManLog("Eat "+ str +"~"); publish(); } function sleep(num){ setTimeout(function(){ lazyManLog("Wake up after "+ num); publish(); }, num*1000); } function sleepFirst(num){ setTimeout(function(){ lazyManLog("Wake up after "+ num); publish(); }, num*1000); } 

The focus here is to solve the delays when calling setTimeout execution, the problem that is the thread that executes asynchronously. Only this method is successful, then a news release publish(), a prompt message queue can be executed. Otherwise, we will have to wait.

4.8 implement the run method for identifying which specific method to be called, it is a total console

// 鸭子叫
function run(option){ var msg = option.msg, args = option.args; switch(msg){ case "lazyMan": lazyMan.apply(null, args);break; case "eat": eat.apply(null, args);break; case "sleep": sleep.apply(null,args);break; case "sleepFirst": sleepFirst.apply(null,args);break; default:; } } 

This method is a bit like a duck distinguish type interfaces , so called comments 鸭子叫.
 The method of receiving a single message run queue, then read out, to see what type of message, and then executes a corresponding method.

4.9 expose interfaces LazyMan, it can make external calls

(function(window, undefined){ // 很多代码... // 暴露接口 window.LazyMan = function(str){ subscribe("lazyMan", str); setTimeout(function(){ publish(); }, 0); return new LazyMan(); }; })(window); 

Interface LazyMan inside publish method must use setTimeout call. This will enable the publish()thread of execution delayed, suspended. Once the chain methods are executed, the thread idle down, and then execute the publish().
 In addition, this is an external interface, so when the call, but also new a new LazyMan, and returned for calls.

V. Summary

1. Benefits

Use the Observer pattern, so that code can be decoupled to a reasonable extent, the post-maintenance more convenient.
 For example, I want to change eatthe method, I just need to focus eat()and LazyMan.prototype.eatimplementation. Elsewhere, I can not focus. This is in line with the minimum knowledge of principles .

2. The lack of
LazyMan.prototype.eat parameters of this approach, in fact, can be used instead of arguments, I did not write it, afraid to get too complex, it leaves the optimization point of it.
 Use the unshift and shift method, without taking into account the low-compatible version of IE browser.

Sixth, the complete source code and online demo

Complete source code has been placed on my gitHub

Entrance Source : https://github.com/wall-wxk/blogDemo/blob/master/2017/01/22/lazyMan.html

demo access address : https://wall-wxk.github.io/blogDemo/2017/01/22/lazyMan.html

demo need to open the console, debugging code in the console.



Author: leon I _ is
the link: https: //www.jianshu.com/p/f1b7cb456d37
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/ygunoil/p/11789363.html