单态(Singleton)是设计模式中最简的模式了,所以我们先拿它开刀。关于什么是Singleton,可以简单参看 Implementing the Singleton Pattern in C#,要系统了解属于就属于设计模式的范畴了,不是本文要讲解的内容。
不过对于C#,当然也包括Java等其它纯面向对象语言,由于其类的构造函数(constructor)不是一个普通的函数(不能自定义其返回值),所以它们在编写Singleton类时都需要使用一个 static的属性或方法来获取对象的实例。而JavaScript中类的constructor就是一个普通的函数,我们可以改变它的返回值来实现对象实例的返回,而不依赖于语言机制。这是到底是什么意思呢 先看一下JS的Singleton类的实现就明白了,示例代码如下:
<
script
language
="javascript"
>
function Singleton()
{
// template code for singleton class.
if ( this.constructor.instance )
{
return this.constructor.instance;
}
else this.constructor.instance = this;
/**//**//////
this.value = parseInt(Math.random()*1000000);
this.toString = function()
{
return '[class Singleton]';
}
}
Singleton.prototype.GetValue = function()
{
return this.value;
};
Singleton.prototype.SetValue = function(value)
{
this.value = value;
};
</ script >
function Singleton()
{
// template code for singleton class.
if ( this.constructor.instance )
{
return this.constructor.instance;
}
else this.constructor.instance = this;
/**//**//////
this.value = parseInt(Math.random()*1000000);
this.toString = function()
{
return '[class Singleton]';
}
}
Singleton.prototype.GetValue = function()
{
return this.value;
};
Singleton.prototype.SetValue = function(value)
{
this.value = value;
};
</ script >
前面说的"改变它的返回值来实现对象实例的返回",就是指的在JavaScript类的constructor类可以 return this .constructor.instance;。所以JavaScript实现的Singleton类在使用时只管new就行了,而不用使用ClassName.Instance或ClassName.GetInstance()这样的语法。
类Singleton的测试代码如下:
var
singleton
=
new
Singleton();
alert(__typeof__(singleton));
alert(singleton.GetValue());
var singleton = new Singleton();
alert(singleton.GetValue());
singleton.SetValue( 1000000 );
var singleton = new Singleton();
alert(singleton.GetValue());
var singleton = new Singleton();
alert(singleton.GetValue());
alert(__typeof__(singleton));
alert(singleton.GetValue());
var singleton = new Singleton();
alert(singleton.GetValue());
singleton.SetValue( 1000000 );
var singleton = new Singleton();
alert(singleton.GetValue());
var singleton = new Singleton();
alert(singleton.GetValue());
返回结果为:Singleton,586606,586606,1000000,1000000。第二个和第三个是random出来的,反正肯定是一样的两个数(__typeof__的实现来自这里: 获取JavaScript用户自定义类的类名称)。