什么是ActionScript 3中实现Singleton模式类的最佳方法是什么? [英] What is the best way to implement a singleton pattern class in Actionscript 3?

查看:243
本文介绍了什么是ActionScript 3中实现Singleton模式类的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于砷不允许私人构造,似乎建立一个独立的,并保证不通过新明确创建的构造函数的唯一方法是通过一个单一的参数,并检查它。

Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.

我听说过两个建议,一个是翻查来电,并确保它的静态getInstance(),另一种是有私人/内部类在​​同一个包的命名空间。

I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.

在构造函数中传递的私有对象似乎preferable,但它并不像你可以有一个私有类在同一个包。这是真的?而更重要的是它实现单的最好方法是什么?

The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?

推荐答案

的enobrev的回答略有调整是有实例作为一个getter。有人会说,这是更优雅。此外,eno​​brev的回答将不会强制执行单身,如果你的getInstance调用之前调用构造函数。这可能不是很完美,但我已经测试了这一点,它的工作原理。 (肯定是有另外一个好办法做到这一点的书高级ActionScrpt3设计模式太)。

A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).

package {
    public class Singleton {

    private static var _instance:Singleton;

    public function Singleton(enforcer:SingletonEnforcer) {
		if( !enforcer) 
		{
				throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); 
		}
    }

    public static function get instance():Singleton
	{
		if(!Singleton._instance)
		{
			Singleton._instance = new Singleton(new SingletonEnforcer());
		}

		return Singleton._instance;
    }
}

}
class SingletonEnforcer{}

这篇关于什么是ActionScript 3中实现Singleton模式类的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆