码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript单例模式

时间:2015-08-09 23:55:36      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

一、什么是单例

  意思是指获取的对象只有一份。

二、最通用的单例 

任何时刻获取SingLeton.instance都是同一个对象

1  var SingLeton={
2        instance:{
3             property:1,
4             getProperty:function(){return this.property;}
5         }  
6 }

三、转变成通过函数的方法来获取对象

类似于SingLeton()(),但是问题来了,每次执行都会重新创建instance对象,如果已经存在那么无需再创建

var Singleton=function(){
    var instance={
        property:1,
        getProperty:function(){return this.property;}
    };

    var getInstance=function(){
        return instance;
    }
    return getInstance;

}
console.log(Singleton()());
var Singleton=function(){
    var instance=null;
function createInstance(){ return { property:1, getProperty:function(){return this.property;} }; } var getInstance=function(){ instance=instance||createInstance(); return instance; } return getInstance; } console.log(Singleton()());

问题又来了,怎么不像其他语言那样,通过SingLeton.getInstance()来获取对象呢

四、自调用函数

要想改造成SingLeton.getInstance(),那SingLeton必须一出来就是一个对象,该对象包含一个方法,可以返回instance对象,我们想到采用让函数立即执行的方式


var Singleton=(function(){
    var instance=null;
    function createInstance(){
console.log("create");
return { property:1, getProperty:function(){return this.property;} }; } return { getInstance:function(){ instance=instance||createInstance(); return instance; } } })() console.log(Singleton.getInstance());
console.log(Singleton.getInstance());

//result:
create 
Object {property: 1}getProperty: (){return this.property;}

Object {property: 1}getProperty: (){return this.property;}
 

至此单例出来了,可以验证下

 

 

JavaScript单例模式

标签:

原文地址:http://www.cnblogs.com/webWf/p/itwf.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!