JS design pattern-5. Single Pattern (I don't know it after so long !)

Source: Internet
Author: User

The advantages of the standalone mode have been completely unknown after such a long time! What are the specific advantages of using it? 1. you can use it to divide namespaces (this is often used. use the Branch Technology to encapsulate the differences between browsers (this is really useless, quite fresh) 3. with the help of the single mode, you can organize the code more consistent, easy to read and maintain (this is also used) the most basic single mode the simplest single is actually an object literal. It organizes a group of associated methods and attributes. Copy the code var Singleton = {name: nimei, age: 2, walk: function (){...}, eat: function (){...}} the copy code object can be modified. You can add attributes and methods. You can also use the delete operator to delete an existing member. This actually violates an object-oriented design principle: classes can be extended, but should not be modified. If some variables need to be protected, they can be defined in the closure. Object literal is only one of the methods for creating a single object. Not all object literal volumes are single objects. The literal volume of objects that are used to mimic the associated array or contain data is obviously not single objects. Used to divide the namespace to prevent global declaration modification and replication code/* using a namespace */var common = {findProduct: function (){},...} var findProduct = true; since the Code is copied, even if the same variables are declared outside, the findProduct can be modified to some extent. Prevent other source code modifications. The JavaScript code on the webpage usually uses more than one source, library code, advertisement code, and badge code. To avoid conflicts with your own code, you can define an object that contains all your code. Copy the code var JChen ={}; JChen. common = {// A singleton with common methods used by all objects and modules} JChen. errorCodes = {// An object literal used to store data} JChen. pageHandler = {// A singleton with page specific methods and attributes .} copy code as a dedicated code package. In websites with many web pages, some code is used by all web pages. They are usually stored in independent files; some code is dedicated to a webpage and will not be used elsewhere. It is best to wrap these two types of code in your own single object. We often use Javascript to add functions for forms. For the sake of stability and degradation, we usually first create a pure HTML webpage that does not rely on Javascript and uses the common commit mechanism to complete tasks. Copy the JChen code. regPage = {FORM_ID: 'reg-form', OUTPUT_ID: 'reg-result', handleSubmit: function (e) {e. preventDefault (); // stop the normal form submission var data ={}; var inputs = JChen. regPage. formEl. getElementByTagName ('input'); for (var I = 0, len = inputs. length; I <len; I ++) {data [inputs [I]. name] = inputs [I]. value;} JChen. regPage. sendRegistration (data) ;}, sendRegistration: function (data) {// make Xhr request and call displayResult () when response is recieved ...}, displayResult: function (response) {JChen. regPage. outputEl. innerHTML = response;}, init: function () {JChen. regPage. formEl = $ (JChen. regPage. form_ID); JChen. regPage. outputEl = $ (JChen. regPage. OUTPUT_ID); // hijack the form submission addEvent (JChen. regPage. formEl, 'submit ', JChen. regPage. handleSubmit); }}// invoke initialization met Hod after the page loadaddLoadEvent (JChen. regPage. init); copy the code to have private members. Chapter 3rd introduces the practice of creating private members of the class. The disadvantage is that they consume more memory, because each instance has a new copy of the method. However, since a single object will only be instantiated once, it is unnecessary to consider the memory issue to define a private Method for it. This method is too simple to use underline notation. Use the closure to copy the code JChen. dataParser = (function () {// private members var whitespaceRegex =/\ s +/; function stripWhitespace (str) {return str. replace (whitespaceRegex, '');} function stringSplit (str, delimiter) {return str. split (delimiter);} return {// public members stringToArray: function (str, delimiter, stripWS) {if (stripWS) {str = stripWhitespace (str );} var outputArray = stringSplit (str, delimiter); retu Rn outputArray ;}}) (); copy the Code. This single mode is also called the module mode, it can organize a batch of related methods and attributes into modules and divide namespaces. These private methods and attributes can be accessed directly by their names, without having to add this. Or JChen. DataParser before them. These prefixes are only applicable to public members accessing single objects. The single mode mentioned earlier in the inert instantiation technology has another thing in common: single objects are created during Script Loading. For a resource-intensive or configuration-intensive monomer, it is more reasonable to postpone its instantiation until it needs to be used. This technology is lazy loading ). The implementation steps are as follows: 1. move all the code to the constructor method. 2. fully control the call time (exactly what getInstance needs to do) to copy the code JChen. lazyLoading = (function () {var uniqInstance; function constructor () {var attr = false; function method () {}return {attrp: true, methodp: function () {}}} return {getInstance: function () {if (! UniqInstance) {uniqInstance = constructor () ;}return uniqInstance ;}}})(); the copy code Branch Technology Branch is a technology used to encapsulate the differences between browsers in dynamic methods set during runtime. For example, if xhr is frequently used on a website, you must run the browser sniffing code again for each call, which seriously results in a lack of efficiency. It is more effective to determine the browser-specific code at one time during Script Loading. This is exactly what branch technologies do. Of course, the branch technology is not always more efficient. Only one branch is used in two or more branches, and other branches occupy the memory. When considering whether to use the branch technology, you must weigh the advantages and disadvantages of shortening the time and occupying more memory. The following uses the branch technology to implement XHR: copy the code var XHR = (function () {var standard = {createXhrObj: function () {return new XMLHttpRequest ();}}; var activeXNew = {createXhrObj: function () {return new ActiveXObject ('msxml2. XMLHTTP ') ;}}; var activeXOld = {createXhrObj: function () {return new ActiveXObject ('Microsoft. XMLHTTP ') ;}}; var testObj; try {testObj = standard. createXhrObj (); return testObj;} catch (e) {try {testObj = activeXNew. createXhrObj (); return testObj;} catch (e) {try {testObj = activeXOld. createXhrObj (); return testObj;} catch (e) {throw new Error ('no XHR object found in this environment. ');}}}})();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.