There is always some confusion about why we need singleton class instead of using static. I can explain it with few program samples. Lets create a singleton class first.
package {
   import flash.events.*;
   public class Singleton extends EventDispatcher {
    public static var singletonObj:Singleton;
    public static function getInstance():Singleton {
       if (singletonObj==null) {
            singletonObj = new Singleton();
       }
       return singletonObj;
     }
    public function callTrigger() {
     dispatchEvent(new Event("onTrigger"));
    }
   }
}


Now lets create other two classes which are going to use this singleton class. Lets say FirstClass.as and SecondClass.as.

FirstClass.as
package {
     import flash.events.*;
     public class FirstClass {
         var singletonObj:Singleton;
         var secClass:SecondClass;
         public function FirstClass() {
             secClass = new SecondClass();
             singletonObj=Singleton.getInstance();
             singletonObj.addEventListener("onTrigger", testEvent);
             singletonObj.callTrigger();
         }
         private function testEvent(evt:Event) {
             trace("FirstClass");
         }
    }
}

SecondClass.as

package {
    import flash.events.*;
    public class SecondClass{
        var singletonObj:Object = new Object();
        public function SecondClass() {
            singletonObj=Singleton.getInstance();
            singletonObj.addEventListener("onTrigger", testEvent);
        }
        private function testEvent(evt:Event) {
            trace("SecondClass");
        }
    }
}

Lets consider we have created an object for FirstClass  somewhere. Inside the constructor function of FirstClass, when callTrigger() function is fired, the singleton class will dispatch the same event for both FirstClass and SecondClass as they are sharing the same object of singleton class. So, by using the singleton we are controlling the two classes with only one central/common object.

singleton.zip
File Size: 8 kb
File Type: zip
Download File




Leave a Reply.