由于AS3不允许私有构造函数,因此它似乎是构造单例并保证构造函数未通过“new”显式创建的唯一方法。是传递一个参数并检查它。

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

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

有帮助吗?

解决方案

enobrev的回答略微适应是将实例作为吸气剂。有人会说这更优雅。此外,如果在调用getInstance之前调用构造函数,enobrev的答案将不会强制执行Singleton。这可能不完美,但我已经测试了这个并且它有效。 (在“Design DesignScrpt3 with Design Patterns”一书中,还有另一种好方法可以做到这一点。

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

其他提示

我已经使用了一段时间了,我相信我最初是从所有地方的维基百科中获得的。

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

这是一个有趣的问题摘要,这导致了类似解决方案

您可以像这样获得私人课程:

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

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

}    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top