Archive

Archive for November, 2008

Extremely safe singleton classes

November 10th, 2008 admin 1 comment

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.

Categories: programming Tags: