Design Pattern in AS3
AS3 Model-View-Controller Implementation:
Most Flex and Flash developers immediately think “MVC” when they here the term “Design Patterns”, and this makes perfect sense considering most of us have either been using MVC for a long time or we have construed our own variations of it’s implementation. What ever the case it is important to understand the basic concepts and implementation of Model-View-Controller.
Model-View-Controller falls under the category of what is known as a compound pattern, that is, a combination of several different Design Patterns to create a named solution. The patterns that make up MVC are typically the Observer Pattern (Model), Strategy Pattern (View and Controller) and the Composite Pattern (View). MVC originated in the Smalltalk-80 language back in the 80’s and it has since been implemented by just about every programming language that requires a user interface, so it is a perfect solution for building Flex Applications.
Implement MVC in Flex Applications is very simple as you can utilize Event dispatching and data binding to simplify invocation between the MVC triad. This allows developers to remove the somewhat awkward Observer pattern which is dependent on passing references of each member throughout the MVC triad.
The MVC paradigm is a way of breaking an application, or more commonly, just a piece of an application’s interface, into three parts: the model, the view, and the controller. Each member is intentionally segregated and represented by an object that is responsible for handling a specific task within the application.
Model: The model is used to manage information and notify observers when that information changes (via data binding).
View: The view is responsible for rendering the model to the user. This is usually rendered as a visual display but a view may also be a sound, a controller vibrating or anything that needs to be conveyed to the user.
Controller: The controller accepts input from the user (via Event Dispatching) and instructs the model and view to perform actions based on that input. In effect, the controller is responsible for mapping end-user action to application response. For example, if the user clicks the mouse button, the controller is responsible for determining how the application should respond.
To view a simple example which demonstrates implementing MVC in Flex 2 / ActionScript 3.0 click here. You can view the source as well as download the example Flex project also.
AS3 Iterator Pattern Implementation:
Every Software Developer iterates over objects on a regular basis. That is, every software developer has the need to loop thru an array or traverse an object at some point during the development of an application. This is obviously a basic part of programming so we usually don’t give it much thought. However, once in while it is good to reflect upon the things that have become routine to determine if there is a common solution out there. We often run into situations where we create an API that consists of a collection of objects that a client may want to iterate over. In order to provide the required functionality we have to define an interface in which the client can iterate over our collection without exposing the collections underlying implementation. This is where the Iterator Pattern comes in handy. Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation. Iterators are intended to remove traversal responsibility out of the aggregate object.
I have created an AS3 Iterator API which consists of an interface (IIterator) that defines the methods which implement the Iterator Pattern. The IIterator interface is implemented by an internal base class (Iterator) which is sub classed by concrete iterator implementations (ArrayIterator, ArrayCollectionIterator and ObjectIterator). I have also provided an IteratorFactory which handles instantiating Iterator sub-classes so that they may be referenced by the same iterator instance.
You can view the example and ASDoc as well as download the swc for the AS3 Iterator API.
AS3 Singleton Pattern Implementation:
Many times when developing you will find that your application calls for a single instance of a class to manage a specific service across the system. For example, let’s say that your application needs to have one single instance of a class that manages all events within the system. Or another scenario could be where the application calls for a single instance of a class to manage all WSDL calls across the system. In order to support the required functionality for the application you would need to create a class that implements what is known as the Singleton design pattern.
The Singleton pattern is implemented by creating a class that has a static public method which instantiates a new instance of the object if one does not exist. If an instance already exists, it simply returns a reference to that object which is a static property of the class, typically named ‘instance’. A best practice naming convention for this method is ‘getInstance();’. To make sure that the object cannot be instantiated in any other way, the constructor is made either private or protected. A Singleton is also considered to be an anti-pattern to some extent as it can be used as a euphemism for a global variable. However, in Object Oriented Programming it is an extreamly useful tool when used correctly.
As I mentioned earlier, the constructor for a Singleton is made either private or protected to restrict it’s access from being instantiated. Since constructors can only be declared as public in ActionScript 3 this is not allowed. A common solution to this is to simply add a inner class within the same file as the class definition and pass an instance of the private class as an argument to the constructor. This way only the getInstance(); method has access to the private class. The only problem with this approach is that the constructor can be called from anywhere within the application with a null value passed in as the argument to the constructor. My solution to this is simple, check that the parameter passed to the constructor is not null. This is how a true Singleton implementation is achieved. The only time that this will not work is if the singleton class is a sub class and the constructor needs to make a call to super. The reason that this will not work is that a call to a super classes constructor must be executed in the very first line of code, therefore a parameter value can not be validated.
Below I have added a simple example demonstrating how to implement the Singleton pattern in ActionScript 3.0:
package
{
public final class Singleton
{
/**
* Defines the unique instance of the class
*/
private static var instance:Singleton;
/**
*
* Singleton constructor which is never to be directly
* instantiated
*
* @param Inner class which restricts constructor
* access to private
*
*/
public function Singleton(access:Private)
{
if (access == null)
{
throw new Error("Singleton Exception…");
}
instance = this;
}
/**
*
* All calls to a Singleton are to be made via
* Singleton.getInstance(); in order to retrieve
* the singleton instance of the Singleton
*
* @return the Singleton of the class
*
*/
public static function getInstance() : Singleton
{
if (instance == null)
{
instance = new Singleton( new Private() );
}
return instance;
}
}
}
/**
* Inner class which restricts constructor access to private
*/
final class Private {}
AS3 Multiton Pattern Implementation:
If you are familiar with the standard GoF Patterns than you are more than likely aware of the Singleton Pattern as well as the solution which it provides.
For those of you who are not familiar with the Singleton Pattern it is a Creational Pattern which, when implemented as prescribed ensures only one instance of a class is ever instantiated. This is facilitated via a single global access point from which a singleton instance is to be created and or retrieved.
You may be wondering just what the Singleton Pattern has to do with the Multiton Pattern? And how does the Singleton pattern relate to the Multiton pattern? What are the differences and what are the similarities?
To answer your question the Multiton pattern is a Creational pattern which builds on the concept of the Singleton pattern by adding a mapping of key / value [object] pairs.
Unlike the Singleton Pattern, whereas there is only ever a single instance of an object created, the Multiton pattern ensures that only a single instance of an object is created per key. Therefore there are multiple instances which are managed via the Multiton object. The Multiton pattern provides centralized access of Multiton objects and advocates keyed storage of objects within a system.
Below is a simple example which demonstrates an implementation of the Multiton Pattern in ActionScript 3.0:
package
{
import com.ericfeminella.utils.HashMap;
import com.ericfeminella.utils.IMap;
public final class Multiton
{
private static var instances:IMap = new HashMap();
public function Multiton(access:Private)
{
if (access == null)
{
throw new Error( "Abstract Exception" );
}
}
public static function getInstance(key:*):Multiton
{
var instance:Multiton=instances.getValue(key);
if ( instance == null )
{
instance = new Multiton( new Private() );
instances.put( key, instance );
}
return instance;
}
public function get id() : *
{
return instances.getKey( this );
}
}
}
class Private {}
Here is a breakdown of the above example.
First a new class is created as well as an additional inner class outside of the package which is used to ensure the constructor can only be called from within the class body, in this case the Multiton class.
{
public final class Multiton
{
public function Multiton(access:Private)
{
// verify that access is not null
// if it is, then an illegal request
// to instantiate the constructor
// is being attempted
if (access == null)
{
throw new Error( "Abstract Exception" );
}
}
}
}
/**
* inner class restricting constructor access to private
*/
class Private {}
Next a private or protected static var of type HashMap (optionally, a generic Object or Dictionary can be substituted) is defined. The static HashMap instance contains the mappings of keys to objects in the Multiton class. Each key only ever contains a single Multiton object instance, and each Multiton instance can only be accessed by it’s associated key.
package
{
import com.ericfeminella.utils.HashMap;
import com.ericfeminella.utils.IMap;
public final class Multiton
{
// contains key / Multiton instance mappings
private static var instances:IMap = new HashMap();
public function Multiton(access:Private)
{
if (access == null)
{
throw new Error( "Abstract Exception" );
}
}
}
}
/**
* inner class restricting constructor access to private
*/
class Private {}
Lastly, Multiton implementation also contains a public static method; getInstance(); which is very similar to the static getInstance() as it applies to the Singleton pattern, but with a slightly different signature. The getInstance(); method in a Multiton requires a single parameter of which specifies the key from which a new instance is to be assigned or retrieved.
Certain Multiton implementations use an object as the key, however it is arguably more intuitive to use a primitive type such as a String to define keys.
package
{
import com.ericfeminella.utils.HashMap;
import com.ericfeminella.utils.IMap;
public final class Multiton
{
private static var instances:IMap = new HashMap();
public function Multiton(access:Private)
{
if (access == null)
{
throw new Error( "Abstract Exception" );
}
}
// retrieve the appropriate Multiton instance
// if the instance does not currently exist
// one will be instantiated and mapped to
// the specified key. All subsequent client
// requests will return the correct instance
public static function getInstance(key:*):Multiton
{
var instance:Multiton=instances.getValue(key);
if ( instance == null )
{
instance = new Multiton( new Private() );
instances.put( key, instance );
}
return instance;
}
}
}
class Private {}
To implement a Multiton instance all that is needed is to invoke the static getInstance(); on the Multiton class object just as one would invoke getInstance() on a singleton class object. However in the Multiton it is assumed that there will be many instances, albeit controlled instances, therefore a key must be specified.
Below is a simple example which demonstrates how to retrieve a specific instance of a Multiton object:
var multiton1:Multiton = Multiton.getInstance( "a" );
trace( multiton1.id ); // a
var multiton2:Multiton = Multiton.getInstance( "a" );
trace( multiton2.id ); // a
var multiton3:Multiton = Multiton.getInstance( "o" );
trace( multiton3.id ); // o
There is not to much documentation on the Multiton Pattern outside of the Ruby community and a Java implementation available on wikipedia, however the Multiton Pattern proves very useful when multiple, controlled object instances are needed.
AS3 Factory Pattern Implementation:
Occasionally when developing Flex applications you will run into a situation where the application calls for certain objects to be instantiated without knowing what type of objects they will be until runtime.
For example, consider the following scenario: You are building a store in which there are multiple products available. You have created various value objects that represent each product in the store, but you have no way of knowing which products a user will select at runtime, therefore you have no way of knowing which VO’s to instantiate? This is a good example of where implementing the Factory Pattern comes in handy.
In case you are not familiar with a Factory Pattern let me give you a quick overview. The Factory Pattern is a creational pattern that models an interface for creating an object which at runtime delegates instantiation to it’s subclasses. This is called a factory pattern since it is intended to “Manufacture” objects. When using the factory pattern your code is loosely coupled since it eliminates the need to embed logic and application specific classes into your code.
For example, you can just as easily add logic to your code that determines which class to instantiate based on the product selected. The only problem with this approach is that you may not want to have the product classes available to the application in general, but rather provide a specific class which is responsible for deciding which class to instantiate, and then return the object to the application. This way your application can stay loosely coupled and the product classes can be abstracted from the application. This approach encourages encapsulation and delegation which is always a good thing in Object Oriented Programming.
Click here to view the source for a basic Factory Pattern implementation in ActionScript 3.0