What is the best way to implement a singleton pattern class in ActionScript 3?

Since AS3 does not allow private constructors, it seems the only way to build a singleton and to ensure that the constructor is not explicitly created via "new" is to pass one parameter and check it.

I heard two recommendations: you need to check the caller and make sure that static getInstance (), and the other - to have a private / inner class in the same package namespace.

The private object passed to the constructor seems preferable, but it doesn't look like you can have a private class in the same package. It's true? And more importantly, is this the best way to implement singleton?

+4
source share
4 answers

A small adaptation of the enobrev response is to have an instance as a getter. Some would say that it is more elegant. Also, enobrev's answer will not apply Singleton if you call the constructor before calling getInstance. It may not be perfect, but I checked it 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{} 
+11
source

I used this for some time, which, I believe, I originally got from Wikipedia of all places.

 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 of the problem, which leads to a similar solution.

+5
source

The pattern that Cairngorm uses (which may not be the best) is to throw an exception at run time in the constructor if the constructor is called a second time. For instance:

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

You can get a private class, for example:

 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
source

Source: https://habr.com/ru/post/1277140/