Extremely safe singleton classes
I’ve found a solution to creating singleton classes that make it absolutely impossible for any class outside it to instantiate it directly.
The idea is that you create an inline class (in this case called ‘SingletonEnforcer’) and require an instance of that inline class as a parameter in the constructor of the singleton class. No class outside of it can instantiate SingletonEnforcer, and therefore no class outside of it can directly instantiate the singleton class itself!
Here’s the example code:
package
{
public class SingletonClass
{
private static var instance : SingletonClass;
public static function getInstance() : SingletonClass
{
if (!instance)
{
instance = new SingletonClass(new SingletonEnforcer());
}
return instance;
}
public function SingletonClass(enforcer : SingletonEnforcer)
{
if (!enforcer)
{
throw new Error(”SingletonClass must be instantiated through SingletonClass.getInstance()”);
}
}
}
}
class SingletonEnforcer {}
I’ve found this example on PixelBreaker’s blog. Check it out.
November 11th, 2008 at 6:11 pm
[...] Extremely safe singleton classes (from rockabit) [...]
January 7th, 2009 at 12:45 pm
Yeah its also in a book - Joey Lotts I think.
Sweet DUUUUUUUDE!