Single-Case mode
A class can have only one instantiated object. such as the PopOver layer on the page, one page only needs one.
Implementation: Create a class that contains a method that creates a new instance object without the presence of an object. If the object exists, this object simply returns a reference to the object.
varSingleton = (functionSingleton () {varInstance =NULL;//Store a reference to a singleton instance
Create a single casefunctionInit () {
Private methods and propertiesfunctionPrivatemethod () {Console.log (' This is a private method! ') } varprivatevariable = ' I am a private variable! 'return {
Public methods and properties Publicmethod:function() {Console.log (' Public ')}, Getprivatevariable:function () { returnPrivatevariable}} } return{getinstance:function () { if(!instance) {Instance=init (); } returninstance; } }})();
This method is not abstract enough, if we need to create a singleton function changes? So we further abstract functions
var function (FN) { varnull; return function () { return Instance | | Fn.call (this, arguments) }}
JavaScript design Pattern---(Singleton mode learning)