[mtasc] Singleton pattern and main()

Roberto Carlos Frias Sobrevilla rcfrias at digitalminds.com.mx
Wed Feb 1 00:15:49 CET 2006


Use the main function as the interface to the singleton:

class Application {

	private static var _instance:Application;
	private static var __parent:MovieClip;

	private function Application(mc:MovieClip) {
		__parent = mc;
	};

	// required by singleton pattern
	public static function main(mc:MovieClip):Application {
		if (_instance == undefined) {
			//trace("new");
			_instance = new Application(mc);
		}
		return _instance;
	}
	public function toString():String {
		return "Application";
	}		
}

 

-----Original Message-----
From: mtasc-bounces at lists.motion-twin.com
[mailto:mtasc-bounces at lists.motion-twin.com] On Behalf Of unit at hdu.co.nz
Sent: Martes, 31 de Enero de 2006 04:22 p.m.
To: mtasc at lists.motion-twin.com
Subject: [mtasc] Singleton pattern and main()

Im having an issue with the Singleton pattern and the main() function. 
When I run the main class (code sample below) I get multiple recursions 
of the function instance() eg: if I uncomment the trace("new") line, it 
is traced twice.
can anyone provide a pointer?


// code begins

class Application {

	private static var _instance:Application;
	private static var __parent:MovieClip;

	private function Application() {};

	// required by singleton pattern
	public static function get instance():Application {
		if (_instance == undefined) {
			//trace("new");
			_instance = new Application();
		}
		return _instance;
	}

	public function toString():String {
		return "Application";
	}

	// init method
	public static function main(parent:MovieClip):Void {
		__parent = (!parent) ? _root : parent;
		var v = instance;
	}
}

// code ends

thanks
D.

-- 
MTASC : no more coffee break while compiling






More information about the mtasc mailing list