A thread about the Singleton Design Pattern arised in the Flashforum (German). We (Nico Zimmermann, Ralf Bokelberg, Florian Kruesch and myself) discussed different implementations of the Singleton Pattern and what the advantages and disadvantages of each are. All started very basic with the simplest implementation all of you probably know.
-
/**
-
* Singleton shows a basic implementation of the Singleton Design
-
* Pattern.
-
*
-
* @author Simon Wacker
-
*/
-
class org.swacker.designpattern.Singleton {
-
/** Stores the onliest instance existing of this class. */
-
private static var instance:Singleton;
-
-
/**
-
* Private constructor to prevent instantiation from outside of
-
* this class.
-
*/
-
private function Singleton(Void) {
-
}
-
-
/**
-
* Returns the onliest existing instance of this class.
-
*
-
* @return the onliest instance of this class
-
*/
-
public static function getInstance(Void):Singleton {
-
// creates a new instance of this class if none exists
-
if (!instance) instance = new Singleton();
-
// returns the stored instance
-
return instance;
-
}
-
}
Then we thought about the problems that emerge using this kind of implementation.
The first problem is that it is awkward to substitute the currently used Singleton with a new one. You had to change ALL references.
The second and maybe not that obvious issue is that only one instance of the Singleton class can exist in the whole project.
You probably think: Why should that be a problem? Doesn’t it lie in the nature of a Singleton that only one instance can exist of it?
These two statements are probably right BUT you normally want to have one instance of the Singleton in one context and not only one in a whole project. Thus my definition of a Singleton would be the following: A Singleton is a class that has exactly one instance in one context. This instance is shared among all classes in that context.
This definition sadly conflicts with the one of GoF (Gang of Four): Ensure a class only has one instance, and provide a global point of access to it.
But I think that the variation is acceptable. My definition maybe reminds you more of the Multiton Design Pattern.
So, how would one implement such a context spcific Singleton. That’s rather easy. You just have to use a factory that decides which instance to instantiate and whether to store this instance for sharing, thus making it a Singleton. You must store the instance of a specific factory global to one context.
-
/**
-
* Singleton is just representing any normal class. It does not have
-
* any specific features.
-
*
-
* @author Simon Wacker
-
*/
-
class org.swacker.designpattern.Singleton {
-
/**
-
* Constructs a new Singleton instance.
-
*/
-
public function Singleton(Void) {
-
}
-
}
-
/**
-
* SingletonFactory is a factory that always returns the same instance
-
* when #getSingleton() is called. This instance thus gets shared among
-
* all referencing classes in the factory’s context. At least if an
-
* instance of the specific class gets obtained via SingletonFactory#getSingleton().
-
*
-
* @author Simon Wacker
-
*/
-
class org.swacker.designpattern.SingletonFactory {
-
/** The shared instance of the Singleton. */
-
private var singleton:Singleton;
-
-
/**
-
* Constructs a new SingletonFactory.
-
*/
-
public function SingletonFactory(Void) {
-
}
-
-
/**
-
* Returns the instance stored in the instance variable ’singleton’.
-
*
-
* @return the Singleton instance shared among all referencing classes
-
*/
-
public function getSingleton(Void):Singleton {
-
if (!singleton) singleton = new Singleton();
-
return singleton;
-
}
-
}
As you can see, what we have done is moving the storing mechanism out of the Singleton and into the SingletonFactory. In our case the class that gets instantiated by the SingletonFactory is hard-coded. We could create a dynamic SingletonFactory to not have to create a new factory every time. The only difference would be that the SingletonFactory’s constructor would take a ‘clazz’ parameter of type Function and return a new instance of the passed class.
That of course isn’t the neatest way to handle the issue. We will now go a step further and use a Context class to bind classes to string identifiers. The Context checks if the class implements the Singleton interface. If that is the case it creates a new SingletonFactory instance assigning the class to it. If you now use the Context.lookup(String) method passing in the identifier, the Factory’s getInstance() operation is being called returning an instance of the assigned class. As you can see this implementation is much more flexible. You do not have to care about whether the class is a Singleton or not. You can also easily substitute the class returned by the Context.lookup(String) method for a given identifier. All you have to care about is that the new class substituting the old one implements the same interface. All this should of course be done declaratively.
A little variation of this approach would be to determine whether to use the SingletonFactory or a normal one not by implementing the Singleton interface but by calling the Context’s bindSingleton() operation or by doing this declaratively. Doing it that way every class could be a potential Singleton without having to change anything inside of it. To achieve all this we need a bunch of new classes and interfaces. These classes or interfaces are:
- Interface org.swacker.designpattern.Singleton:
This interface declares no operations. It is just used to distinguish a Singleton from a normal class. - Interface org.swacker.naming.Context:
The Context interface declares the operations to bind, unbind and rebind an object to a specific name. - Interface org.swacker.naming.Factory:
Factory declares the getInstance() operation that should be implemented by all factories. - Class org.swacker.naming.ClassContext:
ClassContext implements the Context interface. Only classes are allowed to be bound to string identifiers. It gets internally checked whether the passed class is a Singleton using the above explained check mechanism. - Class org.swacker.naming.SimpleFactory:
SimpleFactory is a simple implementation of the Factory interface that just returns a new instance of the passed class, not storing old ones. - Class org.swacker.naming.SingletonFactory:
SingletonFactory stores the firstly instantiated instance of a class and returns this instance every time the SingletonFactory.getInstance() operation gets called.
-
interface org.swacker.designpattern.Singleton {
-
}
-
interface org.swacker.naming.Context {
-
public function bind(name:String, object):Void;
-
public function rebind(name:String, object):Void;
-
public function rename(oldName:String, newName:String):Void;
-
public function unbind(name:String):Void;
-
public function lookup(name:String);
-
}
-
interface org.swacker.naming.Factory {
-
public function getInstance(Void);
-
}
-
import org.as2lib.env.except.Exception;
-
import org.as2lib.util.ClassUtil;
-
import org.swacker.naming.Context;
-
import org.swacker.naming.Factory;
-
import org.swacker.naming.SimpleFactory;
-
import org.swacker.naming.SingletonFactory;
-
import org.swacker.designpattern.Singleton;
-
-
class org.swacker.naming.ClassContext implements Context {
-
private var registry:Object;
-
-
public function ClassContext(Void) {
-
}
-
-
public function bind(name:String, object):Void {
-
if (registry[name]) {
-
throw new Exception("The name [" + name + "] is already in use.", this, arguments);
-
}
-
var factory:Factory;
-
if (ClassUtil.isImplementationOf(object, Singleton)) {
-
factory = new SingletonFactory(object);
-
} else {
-
factory = new SimpleFactory(object);
-
}
-
registry[name] = factory;
-
}
-
-
public function rebind(name:String, object):Void {
-
unbind(name);
-
bind(name, object);
-
}
-
-
public function rename(oldName:String, newName:String):Void {
-
bind(newName, registry[oldName]);
-
unbind(oldName);
-
}
-
-
public function unbind(name:String):Void {
-
if (!registry[name]) {
-
throw new Exception("You tried to unbind a name [" + name + "] that has no binding.", this, arguments);
-
}
-
registry[name] = undefined;
-
}
-
-
public function lookup(name:String) {
-
return Factory(registry[name]).getInstance();
-
}
-
}
-
import org.swacker.naming.Factory;
-
-
class org.swacker.naming.SimpleFactory implements Factory {
-
private var clazz;
-
-
public function SimpleFactory(clazz:Function) {
-
this.clazz = clazz;
-
}
-
-
public function getInstance(Void) {
-
return (new clazz());
-
}
-
}
-
import org.swacker.naming.Factory;
-
-
class org.swacker.naming.SingletonFactory implements Factory {
-
private var instance;
-
-
public function SingletonFactory(clazz:Function) {
-
instance = new clazz();
-
}
-
-
public function getInstance(Void) {
-
return instance;
-
}
-
}
Not every thought has been implemented yet. Including the declarative stuff. The code shown here is also not fully worked out. It are all basic implementations that are right now only intended for explanation reasons. I am planning to offer support for everything I have written above in one of the next releases of the as2lib. If you have any questions or suggestions leave a comment.
To complete this post I’m now going to show you why not just use static methods and variables to implement Singletons. The problems using this approach:
- Everything I told you above would not work using static methods and variables.
- You could not use the constructor to do the core initialization. That means you had to do the core initialization in a static manner. Doing that causes the initialization to be done whether the class is needed or not which would create unnecessary overhead.
- Another major disadvantage is that you could not take advantage of interfaces and inheritance.
- You also could not use ‘this’ directly in one of the static methods becuase it would cause a compile time error. You had to outwit it using eval(”th” + “is”).
This should be enough disadvantages to not even think about implementing a Singleton using static methods and variables.

4 Responses to “DP: Singleton”
A quite good example. It brings issues I haven’t thought about before.
Thanks!!
Nice implementation with nice explanation !
Thanx for it !
Thanks for the comments. They prod me on to finalize all the ideas as fast as possible and to add support to do all the stuff declaratively.
I’ll offer it for download as soon as its finished.
Good explanation Simon… i’ll take a closer look to this interesting code.