Actionscript3 Design Patternsthe Singleton

Title: Actionscript3 Design Patterns:The Singleton Date: 2009-11-09 20:25 Author: eamonnfaherty Category: development Tags: actionscript3, design patterns, singleton Slug: actionscript3-design-patternsthe-singleton

Background Reading

The Problem?
You want to ensure you have only a single instance of an object and want global access to it. This may be because the object uses a resource, such as sounds, or because the object needs a lot of configuration, such as a currency formatter, or needs global access, an event dispatcher.

Currency formatter, sound controller, global event dispatcher

The Singleton:

package singletonpattern {

     * @author eamonn faherty
    public class SocketManagerSingleton {
        private static var _instace : SocketManagerSingleton;
        public static function getInstace() : SocketManagerSingleton {
            return _instace;
        private static function ensureInstanceExists() : void {
            if (_instace == null) {
                _instace = new SocketManagerSingleton();
        public function send(message : String) : void {

Example Usage:

package singletonpattern {
    import common.Example;      

     * @author eamonn faherty
    public class SingletonPatternExample extends Example {

        public function SingletonPatternExample() {
            var socket : SocketManagerSingleton = SocketManagerSingleton.getInstace();
            socket.send("Hello world");

Why is it good?
• It works well; if you use an instance protector then you can be sure that only a single instance will exist.
• It is well understood; it is widely used in the actionscript world.
• It is easy to understand; it is a simple pattern that needs little extra code.
• It is easy to implement; actionscript allows us to check the caller of a method and allows us to use private classes.

Why is it bad?
• It tightly couples the classes that use the singleton to the fact that they are using a singleton.
• It is not possible to extend the singleton class if you wanted to add functionality.
• You cannot use your singleton class again; you cannot extend it or reuse it with composition.
• If you are unit testing a class that uses a singleton you need to add some code to your singleton to make testing possible.

Further Reading
Read about the factory and inversion of control patterns.

Published: November 09 2009

  • category:
  • tags:
blog comments powered by Disqus