YoYo Games Wiki

Singleton Pattern

From YoYoGames Wiki

What is a singleton class?
This is a class where only one instance of it can be created, so in the exemple above only one object SingletonClass will be created.

Creating a singleton class is really easy, here is the main structure :

SingletonClass {
// a private static var holding the class instance
  private static var _oI : SingletonClass;
  

//  the constructor is private to prevent external creation
  private function SingletonClass ( Void ) {}


// to retreive your singleton object
  public static function getInstance( Void ) : SingletonClass {
    if ( _oI == undefined ) _oI = new SingletonClass;
    return _oI
  }


  public function aFunction( Void ) : Void {
    trace( "this is a test function" );
  }

}

Now when you're calling the SingletonClass.getInstance() you are accessing your singleton object.
Eg you want to call the aFunction function, you're doing

SingletonClass.getInstance().aFunction()

See you ...