Home > Dev > Waterproof AS 3.0 Singleton

Waterproof AS 3.0 Singleton

November 24th, 2006 Leave a comment Go to comments

While reading Advanced ActionScript 3 with Design Patterns I’ve once again came across the AS 3.0 Singleton solution that has to deal with the absence of private constructors (I’ll save my rage and cursings about who had the idea to remove them for now ;)) and while the authors are using the already well known method of using a SingletonEnforcer class outside the Singleton’s package to verify that the class cannot be instanciated via the constructor they also note that this can be doublecrossed by giving null or undefined as a constructor parameter. As this is rather sub optimal I was wondering why they don’t just check inside the Singleton constructor for a null/undefined argument and throw an exception accordingly?!
I’m sure somebody else had the same idea already but here’s my idea of a waterproof Singleton class that cannot be misused from the outside (As always, if I missed any detail that accidentally breaks hell loose feel free to correct me) …

package
{
	public class WaterproofSingleton {
		static private var _instance:Singleton;

		public function Singleton(singletonEnforcer:SingletonEnforcer) {
			if ((singletonEnforcer as SingletonEnforcer) == null) {
				throw (new Error("Direct instantiation of a Singleton is not allowed!"));
			}
		}

		public static function getInstance():Singleton {
			if (Singleton._instance == null) {
				Singleton._instance = new Singleton(new SingletonEnforcer());
			}
			return Singleton._instance;
		}
	}
}

class SingletonEnforcer {}
  1. November 24th, 2006 at 23:58 | #1

    The ideal solution would throw a compiler error, not just a runtime exception. I think that’s why they decided to forego checking the argument.

  2. November 25th, 2006 at 23:13 | #2

    Yes but we don’t have the compile time checking so it’s still better to have a runtime exception than having nothing, isn’t it?

  3. November 28th, 2006 at 00:07 | #3

    For some additional thoughts on the singleton pattern, I collected them here.

  4. December 6th, 2006 at 05:40 | #4

    Keith, is right. We left out the condition that checks for the null value simply because it doesn’t throw a compiler error. But if you’re cool with just having a runtime error then by all means feel free to add the condition.

  5. December 10th, 2006 at 20:39 | #5

    Danny … cool! One of the authors here! I guess I’m taking it too serious with the Singleton! ;) btw when will you guys upload the source codes for the book?!?

  6. December 11th, 2006 at 13:19 | #6

    We’re working on gathering and posting the code now. Check the site in a couple weeks.

  1. No trackbacks yet.
You must be logged in to post a comment.