在Actionscript 3中实现单例模式类的最佳方式是什么?

问题描述:

因为AS3不允许使用私有构造函数,所以似乎构建单例并保证构造函数不是通过“new”创建的唯一方法是传递一个参数并检查它。在Actionscript 3中实现单例模式类的最佳方式是什么?

我听说过两个建议,一个是检查调用者并确保它是静态getInstance(),另一个是在同一个包名称空间中有一个私有/内部类。

在构造函数上传递的私有对象看起来更可取,但它看起来并不像在同一个包中可以有私有类。这是真的?更重要的是它是实现单身人士的最佳方式?

+1

单身人士是一个坏主意。请勿使用它们:http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html – Glyph 2008-10-15 21:37:54

+1

Glyph - 您指出的文章显示为何隐藏的依赖项是不好,不是为什么辛格尔顿不好。你可以有没有隐藏的依赖关系的单身人士。 – 2008-10-22 18:33:26

enobrev的答案略有改动是将实例作为getter。有人会说这更优雅。另外,如果在调用getInstance之前调用构造函数,enobrev的答案将不会强制执行Singleton。这可能并不完美,但我已经测试过它,它可以工作。 (在“带有设计模式的高级ActionScrpt3”一书中,确实还有另一个好办法)。

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{} 

Cairngorm(可能不是最好的)使用的模式是如果构造函数被第二次调用,则会在构造函数中抛出运行时异常。例如:

public class Foo { 
    private static var instance : Foo; 

    public Foo() { 
    if(instance != null) { 
     throw new Exception ("Singleton constructor called"); 
    } 
    instance = this; 
    } 

    public static getInstance() : Foo { 
    if(instance == null) { 
     instance = new Foo(); 
    } 
    return instance; 
    } 

}  
+1

“私人静态Foo实例;” - 这甚至没有ActionScript – Iain 2008-09-25 11:42:33

你可以得到一个私有类,像这样:

package some.pack 
{ 
    public class Foo 
    { 
    public Foo(f : CheckFoo) 
    { 
     if (f == null) throw new Exception(...); 
    } 
    } 

    static private inst : Foo; 
    static public getInstance() : Foo 
    { 
    if (inst == null) 
     inst = new Foo(new CheckFoo()); 
    return inst; 
    } 
} 

class CheckFoo 
{ 
} 
+0

你实际上并没有在这里创建一个单身人士 – Iain 2008-09-25 11:41:26

+0

呃...是的。我在考虑私人课堂问题,并弄错了真正的问题。现在修好吗? – 2008-09-26 08:34:35

我一直在使用了一段时间,我相信我最初是从各地的*了。

package { 
    public final class Singleton { 
     private static var instance:Singleton = new Singleton(); 

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

     public static function getInstance():Singleton {     
      return Singleton.instance; 
     } 
    } 
} 

Here's an interesting summary的问题,这导致了类似的解决方案。