zoukankan      html  css  js  c++  java
  • javascript单例模式(懒汉 饿汉)

    第一种:懒汉模式

    var Singleton=(function(){
        var instantiated;  //比较懒,在类加载时,不创建实例,因此类加载速度快,但运行时获取对象的速度慢
        function init(){
            /*这里定义单例代码*/
            return{
                publicMethod:function(){
                    console.log('helloworld');
                },
                publicProperty:3
            };
        }
        return{
            getInstance:function(){
                if(!instantiated){
                    instantiated=init();
                }
                return instantiated;
            }
        };
    })();
    /*可在其他类调用公有的方法或属性来获取实例:*/
    Singleton.getInstance().publicMethod();
    Singleton.getInstance().publicProperty = 4;
    console.log(Singleton.getInstance().publicProperty);

    第二种:饿汉模式

    var Singleton=(function(){
        var instantiated = init();  //比较饿,在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快
        function init(){
            /*这里定义单例代码*/
            return{
                publicMethod:function(){
                    console.log('helloworld');
                },
                publicProperty:3
            };
        }
        return{
            getInstance:function(){
                return instantiated;
            }
        };
    })();
  • 相关阅读:
    poj_1836 动态规划
    动态规划——最长上升子序列
    poj_3260 动态规划
    poj_3628 动态规划
    动态规划——背包问题
    poj_2559 单调栈
    poj_3415 后缀数组+单调栈
    poj_2823 线段树
    poj_2823 单调队列
    poj_3250 单调栈
  • 原文地址:https://www.cnblogs.com/rhythm2014/p/3731604.html
Copyright © 2011-2022 走看看