Friday, April 16, 2010

SingleTon design pattern in AS3

Singleton patter is very useful pattern when you need to have only one object of any class in application. You can enforce this by creating a singleton class.

We cannot directly restrict the user to create multiple object of any class in AS3, Since AS3 doesn't support private or protected constructor. AS3 constructor can always be public. So how we can restrict user for creating an object from outside. There is a work around to this. We can achieve this by creating an enforcer class in the same class file. And we will pass the reference of this enforcer class in the constructor of Singleton class. Since the enforce class can be access by same class only. No one can create the singleton class object outside that class.

Following example explain how we can achieve using AS3.


package
{
public class Singleton
{
private static var _instance:Singleton;

public function Singleton (enforcer:Enforcer)
{
if(!enforcer)
throw(new Error("The Class cannot be instantiated."));
}

public static function getInstance():ModelLocator
{
if(!_instance)
_instance = new ModelLocator(new Enforcer())

return _instance;
}
}
}

class Enforcer
{

}

Create a class which will receive a parameter as enforcer class. And create the enforcer class within the same class below the package block. This enforcer class can only be access by the Singleton class only.

As Singleton class object require Enforcer object reference as a paramer, it cannot be created from outside from the Singleton class. We are checking in Singleton constructor body that if enforcer is null, it will throw an error.

This class can be access only by calling getInstance Static method.

To access this class reference use following code snipped.

var singleton: Singleton = Singleton.getInstance();

I hope this will help you in your development.


Singleton patter is very useful pattern when you need to have only one object of any class in application. You can enforce this by creating a singleton class.

We cannot directly restrict the user to create multiple object of any class in AS3, Since AS3 doesn't support private or protected constructor. AS3 constructor can always be public. So how we can restrict user by creating an object from outside. There is a work around to this. We can achieve this by creating an enforcer class in the same class file. and we will pass the reference of this enforcer class in the constructor of Singleton class. Since the enforce class can be access by same class only. No one can create the singleton class object outside that class.

0 comments:

Post a Comment