as3 Singleton Actionscript 3.0中Singleton实现 修正篇

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

as3 Singleton Actionscript 3.0中Singleton实现 修正篇

  2021-03-17 我要评论
想了解Actionscript 3.0中Singleton实现 修正篇的相关内容吗,在本文为您仔细讲解as3 Singleton的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Actionscript,Singleton,下面大家一起来学习吧。
在前面的blog中,代码如下:
复制代码 代码如下:

package Src
{
/**
* Written by Leezhm, 10th February, 2009
* Contact : Leezhm@126.com
*
* An example of singleton class
**/
public class CSingleton
{
// variable
private static var _instance = new CSingleton();
protected function CSingleton()
{
}
public static function getInstance():CSingleton
{
if (undefined != CSingleton._instance)
{
return CSingleton._instance;
}
else
{
throw Error("Could not create the instace!");
}
}
}
}

Rebuild会出现1153:A constructor can only be declared public.错误,错误原因在错误描述语句描述的很清楚,也就是Constructor在Actionscript中只能声明为public。而我当时写的时候,犯了习惯性的错误,因为我学习的C++和C#中写singleton pattern总是将constructor声明为protected或者private,所以也就"理所当然"地这样写了(还是应该好好重视每种编程语言的基础,虽然都是标准的OO语言,但应该还是各有自己的特色的,不然也就没吸引力了)。既然这样,我们就无法保证用户不用new来创建singleton class对象了,在我思考中,同QQ群上一位网友讨论了哈,他给我推荐了一种解决方案,如下:
复制代码 代码如下:

Public function CSingleton()
{
Throw Error("error!");
}

但后来通过自己的测试,发现这样是不行的,Actionscript的异常机制貌似跟C#和C++不同,其实还是创建了对象,即使抛出了Exception(当然我没有很深入的测试,也许结果并不正确,但这里我要推荐另一种在Actionscript中实现singleton pattern的方法)。后来自己在网上找到一本好书《Advanced Actionscript 3 with Design Pattern》,在它的Part III中的Chapter 4中找到了关于Actionscript中singleton的讨论。

由于我们没法把constructor声明为private,那就可以给constructor传递一个private的variable,同样可以达到不能new的目的。但是怎么样才能让一个只对singleton class有private作用域的variable呢,我们要注意Actionscript的一些规则,比如在一个AS文件中只能有一个Package,一个和AS文件同名的Main Class。但我们在AS文件的包外声明一个class,而且这样声明的class只对package中的class有作用域,对包外是不可见的。所以可以如下来写这个Singleton class:
复制代码 代码如下:

package Src
{

/**
* Written by Leezhm, 14th February, 2009
* Contact : Leezhm@126.com
*
* An example of singleton class
**/

public class CSingleton
{
// variable
private static var _instance = new CSingleton(new SingletonEnforcer());

public function CSingleton(enforcer:SingletonEnforcer)
{
}

public static function getInstance():CSingleton
{
if (undefined != CSingleton._instance)
{
return CSingleton._instance;
}
else
{
throw Error("Could not create the instace!");
}
}

}
}

class SingletonEnforcer {}

BTW: 顺便附上一张电子书中关于Actionscript 3中Singleton Pattern Class讲解的照片,如下:
Actionscript 3 Singleton Pattern Class

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们