Singleton Pattern in AS3

Posted on January 22nd, 2008 in Uncategorized by sam

I’m so proud. For the first time I’m having to actually look up a pattern for my coding. I’m implementing the Singleton pattern right now, and have run into a unique problem.

The idea of the singleton is that there will only ever be one instance of this class in the app. On top of that, the instance will not be instantiated until the class is actually needed, so as not to eat extra system resources. Usually, this is accomplished by making the class’s constructor private, and instead implementing a “getInstance()” method, which then calls the the constructor if there is not already an instance of the class. The problem here is, AS3 does not have a concept of private constructors, so there’s no way to prevent other classes from instantiating multiple instances.

The best workaround I’ve found is detailed in this blog post. By creating a private internal dummy class, and checking that it is passed into the constructor, you can at least block external calls at run time.

My code using this method:

public class DrillDownManager {
    private static const instance:DrillDownManager;

    public function DrillDownManager(lock:Class) {
        if (! lock is SingletonLock) {
            throw new Error( “Invalid Singleton access. Use DrillDownManager.getInstance()”);
        }
    }

    public static function getInstance():DrillDownManager {
        if (null == instance) {
            instance = new DrillDownManager(SingletonLock);
        }

        return instance;
    }
}

class SingletonLock {}

So in this case, if any other class tries to instantiate your class, you’ll at least get a runtime error. Also, your IDE should give you a clue that something odd is going on, by the name and type of the constructor’s argument.

  • Digg
  • del.icio.us
  • blogmarks
  • Fark
  • Reddit
  • Slashdot
  • Technorati
  • Propeller
  • StumbleUpon

Post a comment