Avg. Rating 3.4

Problem

You want to ensure that only a single instance of an object exists.

Solution

ActionScript 3 does not support private or protected constructors preventing common implementation techniques for the singleton pattern. By using a static initializer and a check in the constructor, it is possible to ensure only a single instance of a class is created.

Detailed explanation

Inspired by Daniel Hai from Ted Patrick's JAM, under the following license http://www.onflex.org/license.html.
package
{
    public final class Singleton
    {
        private static var _instance:Singleton = new Singleton();

        public function Singleton()
        {
            if (_instance != null)
            {
                throw new Error("Singleton can only be accessed through Singleton.instance");
            }
        }

        public static function get instance():Singleton
        {
            return _instance;
        }
    }
}
Report abuse

Related recipes