Actionscript 3에서 싱글 톤 패턴 클래스를 구현하는 가장 좋은 방법은 무엇입니까?
-
02-07-2019 - |
문제
AS3은 개인 생성자를 허용하지 않기 때문에 싱글 톤을 구성하는 유일한 방법은 "새"매개 변수를 전달하고 확인하는 것입니다.
두 가지 권장 사항을 들었습니다. 하나는 발신자를 확인하고 정적 getInstance ()인지 확인하고 다른 하나는 동일한 패키지 네임 스페이스에 개인/내부 클래스를 갖는 것입니다.
생성자에 전달 된 개인 객체는 바람직한 것처럼 보이지만 동일한 패키지에 개인 클래스를 가질 수있는 것처럼 보이지 않습니다. 이것이 사실입니까? 그리고 더 중요한 것은 싱글 톤을 구현하는 가장 좋은 방법입니까?
해결책
Enobrev의 답변에 대한 약간의 적응은 인스턴스를 getter로 만드는 것입니다. 어떤 사람들은 이것이 더 우아하다고 말할 것입니다. 또한 Enobrev의 답변은 GetInstance를 호출하기 전에 생성자를 호출하면 싱글 톤을 시행하지 않습니다. 이것은 완벽하지는 않지만 이것을 테스트했으며 작동합니다. ( "디자인 패턴을 가진 Advanced 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{}
다른 팁
나는 이것을 얼마 동안 사용해 왔는데, 나는 원래 모든 장소의 위키 백과에서 얻은 것으로 생각합니다.
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;
}
}
}
흥미로운 요약이 있습니다 이 문제는 비슷한 솔루션으로 이어집니다.
SO와 같은 개인 수업을 얻을 수 있습니다.
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;
}
}