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 SingletonWe 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:
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 SingletonInside 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(); } } } |