zoukankan      html  css  js  c++  java
  • JavaScript演示下Singleton设计模式

    单例模式的基本结构:

    MyNamespace.Singleton = function() {
    	return {};
    }();
    

    比如:

    MyNamespace.Singleton = (function() {
    	return 
        { 
        	// Public members.
    		publicAttribute1: true,
    		publicAttribute2: 10,
    		publicMethod1: function() {
    		...
    		},
    		publicMethod2: function(args) 
        	{
    			...
    		}
    	};
    })();
    

    但是,上面的Singleton在代码一加载的时候就已经建立了,怎么延迟加载呢?采用下面这种模式:

    MyNamespace.Singleton = (function() {
    	function constructor() 
        { 
        	// All of the normal singleton code goes here.
    		...
    	}
    	return 
        {
    		getInstance: function() 
            {
    			// Control code goes here.
    		}
    	}
    })();
    

    具体来说,把创建单例的代码放到constructor里,在首次调用的时候再实例化:

    完整的代码如下:

    MyNamespace.Singleton = (function() {
    	var uniqueInstance; // Private attribute that holds the single instance.
    	function constructor() 
        { 
        	// All of the normal singleton code goes here.
    		...
    	}
    	return 
        {
    		getInstance: function() 
            {
    			if(!uniqueInstance) { 
                // Instantiate only if the instance doesn't exist.
        		uniqueInstance = constructor();
    		}
    		return uniqueInstance;
    	}
    }
    })();
  • 相关阅读:
    Entity Framework4.0 (一)概述(EF4 的Database First方法)
    开园第一篇,Hello cnBlog
    汇编学习笔记32
    汇编学习笔记25
    汇编学习笔记33
    汇编学习笔记28
    汇编学习笔记29,30
    汇编学习笔记23
    汇编学习笔记27
    汇编学习笔记31
  • 原文地址:https://www.cnblogs.com/xiaoyang002/p/4135378.html
Copyright © 2011-2022 走看看