> Have anyone got ideas how to implement Singleton pattern in AS3 best? > Constructor in AS3 can only be public or internal, which is not private > anyway
Hey Michael, One way (as mentioned in another email) is to throw an error in the constructor if some restriction has not been met. The following example may not be the *greatest* hack, because there really isn't any way to catch the error that's being thrown. But it's a hack that gets you to a singleton with pretty high confidence that it was created via the factory method. Another (more complicated) alternative is to use some convoluted namespace scheme. Another (less reliable) possibility is to simply pass an argument to the constructor - and throw if the argument is null. I have to admit that I've been one of the most vocal proponents for the private constructor argument, but want to make the point that the Singleton pattern should be avoided whenever possible. It's very difficult to isolate and test singletons, you wind up needing to add a "destroy" method or some such other hack. In my experience, almost every time I find myself leaning toward a Singleton, I find a more elegant OO solution. Here's a pretty good discussion about why to avoid Singletons: http://www.softwarereality.com/design/singleton.jsp I hope this helps. Luke Bayes www.asunit.org <http://www.asunit.org> package { import flash.util.trace; import flash.errors.IllegalOperationError; import flash.util.setTimeout; public class SingletonExample { private static var instance:SingletonExample; public function SingletonExample(isSingleton:Boolean = false) { setTimeout(checkSingleton, 1); } private function checkSingleton():Void { if(this != SingletonExample.instance) { throw new IllegalOperationError("SingletonExample instantiated directly, you should use the static getInstance method instead"); } } public static function getInstance():SingletonExample { if(SingletonExample.instance == null) { SingletonExample.instance = new SingletonExample(true); } return SingletonExample.instance; } public function toString():String { return "Singleton instance created successfully"; } } } _______________________________________________ Flashcoders mailing list [email protected] http://chattyfig.figleaf.com/mailman/listinfo/flashcoders

