On the singleton using JavaScript

Singleton pattern is defined: an object only guarantee that a class, and it provides access to a global access point.

By definition we can achieve a simple singleton

Opaque singleton

var Person = function(name) {
    this.name = name;
}
Person.getInstance = (function(){
    var instance = null;
    return function(name) {
        if (!instance) {
            instance = new Person(name);
        }
        return instance;
    }
})();
var person1 = Person.getInstance('1');
var person2 = Person.getInstance('2');
console.log(person1 === person2);

This is a simple single case, but we found that users have until Person is a singleton class, compared with our traditional new XXX (), an increase of opacity.

Transparent singleton

Look at the code:

var Person = (function(){
    var instance = null;
    var Person = function(name) {
        if (instance) {
            return instance;
        }
        this.name = name;
        this.sayName();
        return (instance = this,instance);
    }
    Person.prototype.sayName = function(){
        console.log(this.name);
    }
    return Person;
})();
was PERSON1 = new Person ( ' 1 ' );
was person2 = new Person ( ' 2 ' );
console.log(person1 === person2);

Here we use an anonymous function returns a Person class, the use of closures and higher order functions to achieve a transparent singleton class Person, now more in line with our traditional new XXX () creates an instance of the class form.

 

But the singleton pattern we described above are more likely to achieve the traditional object-oriented languages, according to the definition in JavaScript singleton, we should take advantage of the characteristics js achieve Singleton pattern is more in line with js.

Singleton pattern in JavaScript

Here to talk about the problem of global variables, for example the window object, we use a window object only when developed on it, where the window is a single JavaScript embodiment, in such var a = {}, the global the obj object is a singleton object, but in the big picture, it will cause a lot of problems, such as behind us redefine obj, it will cover the object before the fall, this is the harm caused by global variables.

To solve this problem, we can deal with the following common approach to the problem:

// use the namespace 
var nameSpace = {
    obj: {}
}
// Use closure 
var _OBJ = (function () {
     return {
        obj: {}
    }
})()

Now we look at a comprehensive single-case model:

var Person = function() {
    return this;
}
var Animal = function(){
    return this;
} 

var SingleProxy = function(Func) {
    var instance = null;
    return function(){
        return instance || (instance = new Func());
    }
}
var CreatePerson = SingleProxy(Person);
var person1 = new  CreatePerson("ss");
var person2 = new CreatePerson('sss');
console.log(person1 === person2);

var CreateAnimal = SingleProxy(Animal);
var animal1 = new  CreateAnimal("cat");
var animal2 = new CreateAnimal('dog');
console.log(animal1 === animal2);

Here I provide a basic template to create a single example, seems to us to do something,

We created SingleProxy function, as long as you want to achieve a singleton class into them, you get a single case, like this one we will not need to be concerned about the internal code of the class is how child (a little magic right)

Of course, as I said, this is a basic template, if you want to refer to reality, but also needs its own extension, for example, we want to save a file, we can be saved to memory a, can also be saved to memory b, but for computer performance consideration, we get a memory or b when, in order to save space, we have the best after the file is stored in the memory of one of the two, do not go get a new memory.

code show as below:

var CacheA = function () {
    this.caches = {};
    this.setCache = function (key, value) {
        caches[key] = value;
    }
    this.getCache = function (key) {
        return caches[key];
    }
}
var CacheB = function () {
    this.caches = {};
    this.setCache = function (key, value) {
        caches[key] = value;
    }
    this.getCache = function (key) {
        return caches[key];
    }
}

var SingleProxy = function (Func) {
    var instance = null;
    return function () {
        return instance || (instance = new Func());
    }
}
var CreateCacheA = SingleProxy(CacheA);
var cachea1 = new CreateCacheA();
var cachea2 = new CreateCacheA();
console.log(cachea1 === cachea1);

var CreateCacheB = SingleProxy(CacheB);
var cacheb1 = new CreateCacheB();
var cacheb2 = new CreateCacheB();
console.log(cacheb1 === cacheb2);

Now you can happily save the file.

Guess you like

Origin www.cnblogs.com/jsydb/p/12520576.html