Flash / Flex / ActionScript/Class/Singleton

Материал из Web эксперт
Перейти к: навигация, поиск

Singleton Pattern

 
package {
  public class Singleton {
  
    static var instanceCount:uint = 0;
    public function Singleton() {
      instanceCount++;
      if(instanceCount == 1) {
        trace("First Singleton class instance");
      } else {
        trace("Singleton class allows only one instance");
      }
    }
  }
     
}



Singleton pattern with getInstance

 
package {
  public class Singleton {
    private static var instance:Singleton;
    private static var allowInstance:Boolean;
    public function Singleton() {
      if(!allowInstance) { 
        throw new Error("Error: use Singleton.getInstance() instead of new keyword");
      }
    }
    public static function getInstance():Singleton {
       if(instance == null) {
         allowInstance = true;
         instance = new Singleton();
         trace("Singleton instance created");
         allowInstance = false;
       } else { 
         trace("Singleton instance already exists");
       }
       return instance;
    }
    public function doSomething():void {
      trace("doing something");
    }
  }
}