Learning design patterns with Actionscript 3: episode 1 – Singleton pattern

In these Christmas holidays I bought some new books, among them I purchased “Actionscript 3 design patterns” (written by William Sanders and Chandima Cumaranatunge) and I’m actually studying this one. I never faced before the world of design patterns (which is, for those that never heard about, a way to write code and solve problems by implementing tested strategies that will guarantee flexibility and extensibility), or better I knew what a design pattern is, but I’m trying to learn to use them for the first time.
Unfortunately the first thing I learned about implementing design patterns in Actionscript 3 is that for some stuff we have to use workarounds, because actually as3 doesn’t provides 2 little useful things: abstract classes (on which most of the patterns are based) and not public constructor (in Java we can declare a class constructor as private, in as3 we must declare it as public), anyway with some little efforts, we can do everything :-)

Another thing I learned is that design patterns provide a way to solve problems and simplify application’s modification/extension but each pattern can be implemented in a little different way from a language to another and from a developer to another, the only thing that must be unchanged is the goal of the pattern and how it is used.
One, or maybe the simplest, pattern around is the Singleton pattern, which is even one of the most used, even without be aware of it, we used something similar. In fact, Singleton pattern is used when a class must be instantiated only one time in the application (for example a shopping cart in an e-commerce website) or better when a class must exists as only one and be accessible everywhere through a “common access point” which is for convenience a static method called getInstance().

With Java a singleton implementation should be something like this:

public class ClassicSingleton {

   private static ClassicSingleton instance = null;

   protected ClassicSingleton() {

   }

   public static ClassicSingleton getInstance() {

      if(instance == null) {
         instance = new ClassicSingleton();
      }

      return instance;

   }

}

(I taken the code above from this article on javaworld.com: http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html)

In Actionscript 3, the best implementation (in my opinion) of a Singleton pattern is the following:

package {

    import flash.errors.IllegalOperationError;

    public class SingletonClass {

        private static var instance:SingletonClass = new SingletonClass();

        public function SingletonClass() {

            if (instance != null) {

                throw new IllegalOperationError("SingletonClass can't be instantiated because is a Singleton. Use getInstance() to retrieve a class reference.");

            }

        }

        public static function getInstance():SingletonClass {

            return instance;

        }

    }

}

In this way if we try to call the SingletonClass constructor by using the new operator:

var mySingletonClass:SingletonClass = new SingletonClass();

we will get the error: “SingletonClass can’t be instantiated because is a Singleton. Use getInstance() to retrieve a class reference.”. So, the only and sound way to retrieve our SingletonClass is to use getInstance():

var mySingletonClass:SingletonClass = SingletonClass.getInstance();

Every time we will use getInstance() the same class reference will be returned, avoiding multiple class instantiations.

This is clear and good, but initially I was wondering why to use a method to retrieve the instance, in my own custom implementation I wrote the following code:

package {

    import flash.errors.IllegalOperationError;

    public class AbnormalSingleton {

        private static var created:Boolean;

        public function AbnormalSingleton()    {

            if (!created) {

                created = true;

            } else {

                throw new IllegalOperationError("AbnormalSingleton can't be instantiated again because is a Singleton.");

            }

        }

    }

}

With my AbnormalSingleton the first goal of the Singleton pattern is reached (you can’t get more than one instance), but the pattern has also a second goal: provide a common access point to the reference, and without the getInstance() method, this goal can’t be accomplished, moreover patterns are used to avoid errors and to be used by several developers in a clear manner. So, my idea was not so smart, because you can use the new operator to instantiate the class for the first time with no errors, but the second time you will get an error, the situation is not clear! Instead with the previous example, is immediately evident that we can’t use the class to generate multiple instance.