JavaScript面向对象编程之Singleton类

    在C#、Java等纯面向对象的语言中,合理使用设计模式将会使我们的模块设计和代码编写更加健壮和清晰。目前JavaScript的编写已经从自身的object-based,被逐渐模拟来很象(至少七八分吧)object-oriented的语言了,所以我们也可以遵照一些设计模式的概念来编写JS代码。

    单态(Singleton)是设计模式中最简的模式了,所以我们先拿它开刀。关于什么是Singleton,可以简单参看 Implementing the Singleton Pattern in C#,要系统了解属于就属于设计模式的范畴了,不是本文要讲解的内容。

    不过对于C#,当然也包括Java等其它纯面向对象语言,由于其类的构造函数(constructor)不是一个普通的函数(不能自定义其返回值),所以它们在编写Singleton类时都需要使用一个 static的属性或方法来获取对象的实例。而JavaScript中类的constructor就是一个普通的函数,我们可以改变它的返回值来实现对象实例的返回,而不依赖于语言机制。这是到底是什么意思呢 emquestion.gif 先看一下JS的Singleton类的实现就明白了,示例代码如下:
ExpandedBlockStart.gif ContractedBlock.gif < script  language ="javascript" > dot.gif
InBlock.gif
function Singleton()
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif    
// template code for singleton class.
InBlock.gif
    if ( this.constructor.instance )
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif         
return this.constructor.instance;
ExpandedSubBlockEnd.gif    }
 
InBlock.gif    
else this.constructor.instance = this;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//**//////
InBlock.gif
    
InBlock.gif    
this.value = parseInt(Math.random()*1000000);
InBlock.gif   
InBlock.gif    
this.toString = function()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif         
return '[class Singleton]';
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif}

InBlock.gif
InBlock.gifSingleton.prototype.GetValue 
= function()
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif    
return this.value;
ExpandedSubBlockEnd.gif}
;
InBlock.gif
InBlock.gifSingleton.prototype.SetValue 
= function(value)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif    
this.value = value;
ExpandedBlockEnd.gif}
;
None.gif
</ script >

    前面说的"改变它的返回值来实现对象实例的返回",就是指的在JavaScript类的constructor类可以 return this .constructor.instance;。所以JavaScript实现的Singleton类在使用时只管new就行了,而不用使用ClassName.Instance或ClassName.GetInstance()这样的语法。

    类Singleton的测试代码如下:
None.gif  var  singleton  =   new  Singleton();
None.gif alert(__typeof__(singleton));
None.gif alert(singleton.GetValue());
None.gif 
var  singleton  =   new  Singleton();
None.gif alert(singleton.GetValue());
None.gif singleton.SetValue(
1000000 );
None.gif 
var  singleton  =   new  Singleton();
None.gif alert(singleton.GetValue());
None.gif 
var  singleton  =   new  Singleton();
None.gif alert(singleton.GetValue());

    返回结果为:Singleton,586606,586606,1000000,1000000。第二个和第三个是random出来的,反正肯定是一样的两个数(__typeof__的实现来自这里: 获取JavaScript用户自定义类的类名称)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值