JavaScript中“单实例模式(单值模型)”的实现

注:本文中部分描述都是操作我的书《JavaScript高级应用与实践》而言,还请朋友们多多支持我的书,详情请见:

博主网站地址:

http://m9m.3322.org/doc/js/md00.jsp

“北京电子工业出版社”地址

http://www.phei.com.cn/bookshop/bookinfo.asp?bookcode=TP061230%20&booktype=main 

function Singleton()
{
   // 不用new则执行if中的语句
   if(this == window)
      return Singleton._instance || (Singleton._instance = new Singleton());

   // .....这里可以放置你的其他代码

   // 用new时执行的语句
   return Singleton._instance || (Singleton._instance = this);
}

// 单实例的static静态获取函数
Singleton.getInstance = function()
{
    return Singleton._instance || (Singleton._instance = new Singleton());
};

Singleton.prototype.name = "xiatian";
Singleton.prototype.dsp = function(){alert(this.name)};

var oTest = Singleton.getInstance();
oTest.dsp();
oTest.name = "summer";

// 可以他看出:new Singleton(),Singleton()或者Singleton.getInstance(),
// 执行的结果相同,都是summer
var oTest1 = Singleton();
oTest1.dsp();

另外的单值模型,则是利用闭包中变量的private特性来设计,它有个缺陷,就是不同的对象需要写不同的代码,
而,上面的模型则比较通用些。如下所示:
var Singleton = (function()
{
  // private的变量
  var uniqueInstance,
  // private的方法
  constructor = function()
  {
    // ... 你可以在这里放许多你需要初始化的代码
  };
  // return和"{"之间的空格可以省略
  return{
    getInstance: function(func)
    {
      // 闭包函数特性:能访问前面定义的private变量和方法
      return uniqueInstance || (uniqueInstance = (func || constructor()))
      // 最后一个语句,也就是"}"前的一个语句的";"可以省略
    }
  }
})();

或者,改良针对不同的对象,这样就比上面两种更加通用了:
var Singleton = new function()
{
  // private的变量
  var uniqueInstance = [],
  // private的方法
  constructor = function()
  {
    // ... 你可以在这里放许多你需要初始化的代码
  };
  // return和"{"之间的空格可以省略
  return{
    getInstance: function(func)
    {
      // 闭包函数特性:能访问前面定义的private变量和方法
      // 同时利用对象作为数组下标,
      // 对象下标特性请见《JavaScript高级应用与实践》电子工业出版社出版,夏天编著
      return uniqueInstance[func] || (uniqueInstance[func] = (func || constructor)())
      // 最后一个语句,也就是"}"前的一个语句的";"可以省略
    }
  }
};

使用:
var MyClass = function()
{
   if(this == window)return new MyClass();
   this.name = "xiatian";
   this.dsp = function()
   {
      alert(this.name);
   };
};
var oTest = Singleton.getInstance(MyClass);
oTest.name = "summer";
oTest.dsp();

var oTest1 = Singleton.getInstance(MyClass);
oTest1.dsp();


var MyClass1 = function()
{
   if(this == window)return new MyClass();
   this.name = "xiatian";
   this.dsp = function()
   {
      alert(this.name);
   };
};

var oTest11 = Singleton.getInstance(MyClass1);
oTest11.name = "summer2";
oTest11.dsp();

var oTest12 = Singleton.getInstance(MyClass1);
oTest12.dsp();


文章出处:http://www.diybl.com/course/1_web/javascript/jsjs/2008410/109068.html

posted @ 2009-01-14 15:07  遥望星空  阅读(254)  评论(0编辑  收藏  举报