Skip to content

Another singleton

2010 May 2
by Sven Busse

Juten Tach,

i know, everybody hates Singletons, and i do, too. But i find it an entertaining exercise to come up with new ways of circumventing the lack of private constructors for Singletons. Today this new one came to my mind:

First, we define an Interface, which specifies, how our Singleton should look like:

IMySingelton.as:

package {
	public interface IMySingleton {
		function doodle(something:String):void;
	}
}

Ok, next we define our Singleton.

myInstance.as:

package {
	public var myInstance:IMySingleton = new MySingleton();
}
 
class MySingleton implements IMySingleton {
	public function MySingleton() {
		trace("MySingleton is now there!");
	}
	public function doodle(something:String):void {
		trace("yippee: " + something);
	}
}

Very simple, isn’t it? We could optionally also go without the Interface, but then we loose code completion in our editors, because the class MySingleton will be ignored by most editors, although it would compile and run just fine. I do agree, that this is not really exactly the idea of a Singleton, because it has no getInstance() method, but in the end, the result is the same, we only have one global instance of MySingleton.

And since the variable is already global, we don’t even have to declare it in our class, we can directly use it:

Main.as:

package {
	import flash.display.Sprite;
 
	public class Main extends Sprite {
		public function Main() {
			myInstance.doodle("loodle");
		}
	}
}
2 Responses leave one →
  1. May 8, 2010

    Thanks for this snippet, very useful!

Trackbacks and Pingbacks

  1. Tweets die Another singleton | Ghost23 Blog erwähnt -- Topsy.com

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS

*