Flex -- The Singleton Design Pattern

One of the design patterns in the Object-Oriented-Programming languages like ActionScript 3.0.
The Singleton design pattern is used to limit a class to one instance and provide global access to that instance
Common examples include classes that manage resources that are intrinsically singular such as

1. Selection focus
2. Navigation history
3. Window depth
4. Class that manages the state of user?s cursor
5. Class that loads application setting from an XML file and provide access to those settings

Essential features of Singleton class

? A private static property that holds the single instance of the class
? A public static method that provides access to the single instance if it?s created and creates the single instance if it hasn?t been created yet
? A way of restricting access to instantiating the class


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.

package mypackage
{
public class SingletonExample
{
public function SingletonExample(enforcer:SingletonEnforcer)
{
}

private static var _instance : SingletonExample;

public static function getInstance():SingletonExample
{
if (_instance == null)
_instance = new SingletonExample(new SingletonEnforcer());

return _instance;
}
}
}
class SingletonEnforcer {}

Comments

Popular posts from this blog

Protopage a great iGoogle Alternative

A simple Flex Builder contact form

Designing a Better Contact Page