Friday, January 16, 2009

Singleton in Flex and its Usage

What is singleton pattern?

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. If you create the class as a singleton then no way to create more than one instance. But, you can get that single instance in any number of classes. So all the classes will share the same properties and behaviours of that singleton object.

How to implement the singleton pattern?

Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made protected (not private, because reuse and unit test could need to access the constructor). Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.
The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.

How to implement the singleton pattern in Flex and ActionScript?

  • Can we implement the singleton pattern in ActionScript? Why not? Ofcource we can.
  • Is there any keyword named as singleton in Flex?. No.
  • Can we declare the constructor as protected in Flex?. No. (ActionScript 3.0 will not support protected constructors)
  • Can we declare the constructor as private in Flex?. No. (ActionScript 3.0 will not support private constructors)
  • Then how can we implement the singleton pattern in Flex ? See the next line.

Steps to implement the singleton pattern in Flex and ActionScript

Consider the MySingleTon class as a singleton class.

package {
public class MySingleTon {

// Single Instance of Our MySingleTon
private static var instance:MySingleTon;

//DEFINE YOUR VARIABLES HERE
public function MySingleTon (enforcer:SingletonEnforcer)
{
if (enforcer == null)
{
throw new Error( "You Can Only Have One MySingleTon" );
}
}

// Returns the Single Instance
public static function getInstance() : MySingleTon
{
if (instance == null)
{
instance = new MySingleTon ( new SingletonEnforcer );
}
return instance;
}
}
}

// Utility Class to Deny Access to Constructor
class SingletonEnforcer {}

1). We should create one static variable. It will be called "instance" and it will be of type MySingleTon. This will be the variable where we will store our
one instance of our class.

2). Then we should create one constructor. The constructor takes one argument - "enforcer". You will notice that this "enforcer" has a type of "SingletonEnforcer"
which is defined directly after our class. Here is the logic behind that:
  • When you put a class in an Actionscript file below the main class, it is only available to that class.
  • If the constructor requires this argument - then only our main class can create an instance of itself, because we do not have access to the “SingletonEnforcer” class. Only the main class has this access.
  • We will not access our class in the normal way by using the “new” statement because we can’t call the constructor. Once we get inside of the constructor, we have a few lines that make sure things work as planned. The “if” statement ensures that we had a valid “enforcer” passed in. If there wasn’t it throws an Error stating that “You Can Have Only One MySingleTon”.

Then we should create one static function named as getInstance. The “getInstance” function is how we will access our MySingleTon from our application. This function simply passes back the “instance” of the class. If it doesn’t exist yet, it creates it. We can now get the MySingleTon by using the following:

var mySingleTone:MySingleTon = MySingleTon.getInstance();. So you can share this single object in any number of classes.

PureMVC and Guidelines

PureMVC is a framework which helps the Flex programmers to create applications in the MVC architecture. It helps the programmers to develop loosely coupled components. It helps to create the resusable codes. Very easy to understand and maintain than other frameworks. Forces the singleton pattern.

We can divide the pureMVC as:

  • Facade & Core
  • Controller & Commands
  • Model & Proxies
  • View & Mediators
  • Observers & Notifications

Steps to follow in PureMVC

1. Main application should call the facade.startup(this). Here facade is the singletone instance of ApplicationFacade class.

2. ApplicationFacade

  • Singleton class.
  • It extedns the org.puremvc.as3.patterns.facade.Facade.
  • It implements org.puremvc.as3.interfaces.IFacade .
  • Should override the initializeController() method.
  • It defines static constants for Notification names.
  • Initializes the Commands used to access and notify the Commands, Mediators and Proxies.

3. MacroCommand(s)

  • It extends the org.puremvc.as3.patterns.command.MacroCommand.
  • It implements the org.puremvc.as3.interfaces.ICommand.
  • Should override the initializeMacroCommand() method.
  • Executes the SimpleCommands and MacroCommands.
  • User can registerand retrieve the Mediators and Proxies.

4. SimpleCommand(s)

  • It extends the org.puremvc.as3.patterns.command.SimpleCommand.
  • It implements org.puremvc.as3.interfaces.ICommand.
  • Should override the execute( note:INotification ) method.
  • User can register and retrieve the Mediators and proxies.

5. Mediator(s)

  • It extends the org.puremvc.as3.patterns.mediator.Mediator.
  • It implements the org.puremvc.as3.interfaces.IMediator.
  • Should override the listNotificationInterests() and handleNotification( note:INotification ) methods to listen to the notifications.
  • Registers the mediators and proxies.
  • User can retrieve the Mediators and proxies.
  • User can register the notifications.
  • Listens for the notifications from other Mediators, Proxies and commands.
  • Listens for the events from the component.
  • Sends the notifications to other mediators.

6. Proxy(ies)

  • It extends org.puremvc.as3.patterns.proxy.Proxy.
  • It implents the interface org.puremvc.as3.interfaces.IProxy.
  • User can send the notifications.
  • Used to access the Delegates and datas.

7. Component(s)

  • Views of our application.
  • Every component should have its own Mediator. One Mediator per Component.
  • Dispatches the event. So the mediator can listen for that events.

Observers

PureMVC applications may run in environments without access to Flash’s Event and EventDispatcher classes, so the framework implements an Observer notification scheme for communication between the Core MVC actors and other parts of the system in a loosely-coupled way. No need to create instance for the Observers and notificatios. These are inbuilt things in the pureMVC.

Notifications
PureMVC implements the Observer pattern so that the Core actors and their collaborators can communicate in a loosely-coupled way, and without platform dependency.

Not simply a replacement for Events, Notifications operate in a fundamentally different way, and work synergistically with Events to produce extremely reusable View Components that need not even know that they are coupled to a PureMVC system at all if engineered properly.

Events are dispatched from Flash display objects that implement the IEventDispatcher interface. The Event is ‘bubbled’ up the display hierarchy, allowing the parent object to handle the Event, or the parent’s parent, etc.

Notifications are sent by the Facade and Proxies; listened for and sent by Mediators; mapped to and sent by Commands. It is a publish/subscribe mechanism whereby many Observers may receive and act upon the same Notification.

WorkFlow of the PureMVC framework

  • MainApplication should startup the pureMVC framework by calling the ApplicationFacade(Facade)’s startup method.
  • ApplicationFacade Registers the Commands,Mediators and Proxies.
  • User can retrieve the Mediators and Proxies in the ApplicationFacade.
  • Two commands are there: MacroCommand and SimpleCommand.
  • MacroCommand registers other commands, Mediators and Proxies.
  • SimpleCommand registers the Mediators and Proxies.
  • Both the Macro and Simple Commands can be used to retrieve the Mediators and Proxies.
  • User can send notifications from both the Macro and Simple commands.
  • Mediators registers the component with the PureMVC.
  • Mediators will listen for the events and notifications.
  • Mediators will listen for the events dispatched from the Components.
  • Mediators will listen for the notifications sent from the other Mediators, Proxies and Commands.
Courtesy:ponbharathi