Documentation and Books

Recent site activity

How to implement the Singleton design pattern?

The Singleton design pattern is used to restrict instantiation of a class to only one Object (it could be more but the class that is created to be a singleton has control over the number of instances). This is useful when you only need exactly one object to coordinate actions across the system.

Common use of the Singleton design pattern is for example a database connection pool or Facade objects.

Class Diagram:

 Singleton
 - singleton : Singleton
 + getInstance() : Singleton

The implementation is normally quite simple for a number of languages, however in Flex it can be a challenge. The problem that you encounter in Flex is that a Singleton normally has a private constructor so that you disable to possibility of instantiating the class using the new keyword. However when you make the constructor in Flex private it will give compilation errors when you are trying to instantiate the class from within the getInstance method.

The following example of a Singleton solves the solution of the private constructor and disallows a user from creating new instances:

package nl.sodeso.singleton {

    public class MySingleton {

        private static var instance:MySingleton;

        public function MySingleton(enforcer:SingletonEnforcer() {
            if (enforcer == null) {
                throw("It is not allowed to instantiate the MySingleton class, use MySingleton.getInstance.");
           }

            // Place initialization code here.
        }

        public static function getInstance():MySingleton {
            if (instance == null) {
                instance = new MySingleton(new SingletonEnforcer());
            }

            return instance;  
        }
    }
}

class SingletonEnforcer{}

Do notice that both classes are within the same actions script class file!

So what do we have here, first of all we have solved the private problem, by forcing the user to pass in a SingletonEnforcer we blocked the user from using the constructor for two reasons, first of all the user cannot instantiate the SingletonEnforcer class since it is a member for the MySingleton class so only the MySingleton class can instantiate it. However we have to check the enforcer argument that it is not null since this is still alowed.

When the user uses the getInstance method it first checkes if the instance variable is filled, if not we create a new instance of the MySingleton class and store it in this variable. We then return the reference to this instance back to the user.