tutorials fle singlt

Implementation of the Singleton pattern

We are going to find out how to use the Singleton pattern to implement it in AS3.

A simple definition of the Singleton pattern: a unique object and global accessOur first reflex is to go and look on Google but we always find a Java-specific implementation … and we are in Actionscript 3 (AS3). We are therefore going to take into account the specifics of the language.

The first specific is that we only have one access attribute to the constructor who is “public”. We will have to find a solution to this first problem.

Here is an implementation which manages to lock the access to our Singleton’s constructor:

// Logger.as
package iteratif.logging {
	public var Logger:LoggerImpl = new LoggerImpl();
}
 
// We put the class outside of the package but in the following file: Logger.as
internal class LoggerImpl {
	public function LoggerImpl() {
 
	}
 
	public function log(msg:String):void {
		trace(msg);
	}
}

We are allowed to put as many internal classes as we want in an .as file, which means that we only have access to the classes from this same file.

This implementation does not prevent the deletion of this object; to rectify this we will declare the Logger as a constant:

package iteratif.logging {
	public const Logger:LoggerImpl = new LoggerImpl();
}

The disadvantage of this implementation is that only the Logger.as file recognises the LoggerImpl class, preventing any form of inheritance. Another implementation of Singleton in AS3 could be envisaged without making the class external to the package but by using a metadata [ExcludeClass]. This would allow us in this case to specialise (inherit) in the singleton:

// Fichier LoggerImpl.as
package iteratif.logging {
	[ExcludeClass]
public class LoggerImpl {
	public function LoggerImpl() {
 
	}
 
	public function log(msg:String):void {
		trace(msg);
	}
}
}
 
// Fichier Logger.as
package iteratif.logging {
	public const Logger:LoggerImpl = new LoggerImpl();
}

The metadata just excludes the class from the code-completion in the Flex builder editor; of course if you know the path to this class, nothing is stopping you from instantiating it.

It is important to take into account specifics of a language and what you use in one language is not necessarily applicable for another.

By ITERATIF - BUGALOTTO Olivier (2007) You can find this tutorial and comments on the subject here :Implementation of the Singleton pattern in AS3 (Flash, Flex and AIR)








Adobe Training center


Mediabox Training Centre © 2000 - 2008 All rights reserved.
Adobe Authorized Training Centre. State convention under number 25 14 02167 14.
Mediabox : SARL au capital de 62.000€ - Activity number: 25 14 02167 14 - SIRET : 493 716 468 00027
MEDIABOX, 102 Avenue des Champs Elysées, 75008 PARIS - Tel. +33(0)2.31.91.96.89 - Fax. +33(0)2.72.68.56.42