JavaScript Design Pattern Learning--Singleton mode

Source: Internet
Author: User
Tags closure jquery library

Singleton mode, also known as the singleton mode, is an object class that allows instantiation only once.

Use:

1. Use an object to plan a namespace (for example, the jquery library, which provides a namespace for it), and to manage properties and methods on objects in an orderly manner.

2. Manage each module of the code base through a singleton mode

The concept of modularity has been around for a long time, and it has been used historically in JS. Often when we write code, complex problems are logically split according to the actual situation, making the code more readable and maintainable. So a module can be understood as part of the whole. And with the increase of the complexity of JS application, the application of modularization has become a must.

In the previous JS, not specifically for modularity to provide the appropriate syntax support, but fortunately we have closures. So we used to simulate a module with a self-executing function.

  
var moduledemo = (function  name (params) {    function  Bar () {};     function foo () {};     function map () {};     return {        Bar:bar,        Foo:foo,        map:map,    }}); // access the method inside the module moduledemo.bar ();

Bar,foo,map three methods are defined inside a function, but can be used externally. So it's easy to see that we implemented the module with closures. With this idea, we can encapsulate some tool methods to form a separate tool module to avoid repetitive coding. Such a more well-known practice has lodash, axiossuch as  They are all tool modules that are used more in practice. Modularization is a practical application of single-case mode.

3. Managing Static variables

Static variable features: Only access cannot be modified, can be used after creation

---JS implementation method, defined within the function, can only be accessed through privileged methods, does not provide a method of assigning variables, only provides a way to get the variable

And in order to be able to access after creation, let the created function execute once, at this time, we create the object to save the static variable through the accessor access, and finally put the object as a singleton in the global space as a static variable singleton object for others to use

(Create a good, regardless of the need to exist in memory this singleton object------commonly known as "Bad Han Mode")

Code Demo: The main use of a self-executing a closure, self-executing guarantee can be used after creation, while the closure can protect data, data access, through the closure of the method of returning a accessor (with the closure to implement a singleton mode)

var config = (function() {            var conf = {                                0,                 ,            }            return  {                // accessor method                function (name) {                    returnnull;}}        }) ()

4. Inertia single case

While some singleton objects need to be created lazily, someone also calls it "lazy creation" (if you have already created it, just return it, if it is not created, create one, create it when needed---------commonly known as "lazy Mode")

        //Lazy Loading single case        varLazysingle = (function (){            //Single Instance reference            var_instance =NULL; //Single Case            functionSingle () {/*private properties and methods are defined here*/                return{publicmethod:function() {}, Publicproperty:' 1.0 ',                }            } //get an interface for a singleton object            return function() {                //If this is not the single case Jiujiang create a singleton mode                if(!_instance) {_instance=Single (); }                return_instance; }}) () Console.log (Lazysingle (). Publicproperty)

Above, you can summarize the advantages of the singleton pattern:

1. Define namespaces for easy management and maintenance

2. Compared to each new object comes out, can greatly reduce memory, reduce the use of resources

JavaScript Design Pattern Learning--Singleton mode

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.