最近在做项目的时候,写了个单态类。可是在后来的使用中,不小心在获取实例的时候
加了一个new,居然不会出错。但是就没有想象中的结果了。一直调试程序都没发现。
知道后来才知道。现在把它写下来,让大家看看。讨论讨论
先来个单态类
class Single
{
private static var single:Single;
private static var count:Number = 0;
//私有,不能再使用new
private function Single()
{
count++;
}
//获取实例
public static function getSingle():Single
{
if(single == undefined)
{
single = new Single();
}
return single
}
public static function testMethod()
{
trace("测试方法!");
return true;
}
public function getCount()
{
trace("count:" + count);
}
}
//test
//var s1:Single = new Single();
var s1:Single = Single.getSingle();
trace(s1);
s1.getCount();
var s2:Single = Single.getSingle()
s2.getCount();
trace(s1 == s2);
//可以看出,s1和s2都是同一个实例
//照常理,构造器是私有的,那么就不能使用new了。可是flash我有很多不了解的地方
//请看下面的例子吧
var s3 = new Single.getSingle();
trace("s3:" + s3);
trace(s3 == s1)
//很明显,在这样的情况下可以使用new(注意,如果是java程序的话,是不允许的)
var s4 = new Single.testMethod();
trace("s4:" + s4);
//我的理解是,在这里使用new,不再是针对Single的构造器了
//不过我还是很有很多不了解的地方,毕竟不熟悉flash的机制。希望有理解的朋友
//可以讨论一下