Building a Simple Singleton


Often a good example will go a long way when learning a design pattern. In the next few sections we'll look at an example using the Singleton pattern.'' In the first example, we simply create a generic Singleton and invoke it.

Creating the Singleton

We first need to create the Singleton class. Create it in the com.peachpit.aas3wdp.singletonexample package and name it Singleton. Notice that this class has all the standard elements of an ActionScript 3.0 Singleton class:

  • A private static property, _instance, to hold the single instance of the class.

  • A constructor with a parameter typed to a class, SingletonEnforcer, that is available only to the Singleton class. The SingletonEnforcer class definition is also required.

  • A public static method, getInstance(), that provides access to the single instance and creates it if it does not exist.

The following code shows an example of standard singleton class. We'll us this to demonstrate how to build a singleton class.

package com.peachpit.aas3wdp.singletonexample {    public class Singleton {       static private var _instance:Singleton;       public function Singleton(singletonEnforcer:SingletonEnforcer) {}       public static function getInstance():Singleton {          if(Singleton._instance == null) {             Singleton._instance = new Singleton(new SingletonEnforcer());          }          return Singleton._instance;       }       public function doSomething():void {          trace("SOMETHING!");       }    } } class SingletonEnforcer {}


As you can see, the doSomething() method is a public method that simply traces the text "SOMETHING!" to the console. While this example is very simple, it demonstrates the required elements of a class that follows the Singleton design pattern in ActionScript. The code in the next section demonstrates how to invoke a Singleton class.

Note

In order for trace statements to output information to the console you must debug the application rather than just run it.


Invoking the Singleton

Inside the main class, we're going to get the instance of the Singleton class and call a method on that object. We start by importing the Singleton class. Then inside the constructor, we call the Singleton's static getInstance() method and immediately call the doSomething() method on the returned instance. The doSomething() method simply traces "SOMETHING!" to the console.

package {    import com.peachpit.aas3wdp.singletonexample.Singleton;    import flash.display.Sprite;    public class SimpleSingletonExample extends Sprite {       public function SingletonExample() {          Singleton.getInstance().doSomething();       }    } }





Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net