views:

7190

answers:

11

What real (i.e. practical) difference exist between a static class and a singleton pattern?

Both can be invoked without instantiation, both provide only with one "instance" and neither of them is threadsafe. Is there any other difference?

+1  A: 

Singleton's are instantiated, it's just there's only one instance ever instantiated, hence the single in Singleton.

A static class can't be instantiated by anything other than itself.

Kezzer
+10  A: 

In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.

Quick Example:

if( useD3D )
    IRenderer::instance = new D3DRenderer
else
    IRenderer::instance = new OpenGLRenderer
Don Neufeld
It's not really a singleton pattern, looks more like factory to me.
vava
Not really, the fundamental difference between the two is that the Singleton will "cache" its single object and keep returning (a reference to) the same one. The Factory pattern will create new instances.
Mystic
Then it's proxy-singleton :)
vava
Hmm, I know this variety of the Singleton as MonoState.
Huppie
+25  A: 

What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

Jon Skeet
Well, if you prefer it, neither is inherently threadsafe, you have to make them be threadsafe, both of them, so no difference there.
Jorge Córdoba
Can you give an example of something which *is* inherently threadsafe, other than immutable types?
Jon Skeet
Even some immutable types are not thread safe if they are copies themselves of a mutable object.
WolfmanDragon
Jon, by "inherently" I mean from the programmer/user point of view. Lots of system calls or library classes are threadsafe so I don't have to worry about it... but you're right, I can't think of anything
Jorge Córdoba
@WolfmanDragon: I'm not sure I'd call that an immutable type, but yes, it gets woolly. Eric Lippert has a great post about different varieties of immutability.
Jon Skeet
To Skeet: People saying that singleton isn't threadsafe mean that a singleton is shared between threads *unnecessarily* all the time, while stack objects get shared when you need them to, which means you don't have to do unneeded synchronization.
@Iraimbilanja: At that point it all becomes language and platform specific, I'd say.
Jon Skeet
+2  A: 

The true answer is by Jon Skeet, on another forum here.

Kezzer
I'm glad to see I'm consistent :)
Jon Skeet
And it's over three years old.
Kezzer
+2  A: 

The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

neil.johnson
+4  A: 

A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.

Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.

Morendil
polymorphism doesn't come into play with singletons at all
So you think. I think differently. ;) For instance, imagine a singleton factory that returns an interface. You know you're getting an ISingleton (and it's the same one forever) but not necessarily which implementation.
Morendil
A: 

Depending on the language implementation and your usage patterns, a Singleton might be less efficient due to the overhead of calling the getInstance() method each time you want to use it (although probably in most cases it doesn't matter).

too much php
A: 

In terms of how they can be used, a short example would be this.

If the object is going to exist throughout the entire lifetime of the program, and you only need one of it, it should be static

If the object needs to be used more than once, in more than one place, and its lifetime may be short or long, make it an instance

Example of a static object would be a class that manages your programs configuration, or a "service object" throughout your programs lifetime

Or, if the property, object, or method does not rely on anything other than non-static data, it should be static.

Example of this:

public static Boolean SupportsIPv6 { get { return Socket.OSSupportsIPv6; // static } }

David Anderson
A: 

Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated. As far as I know static methods (static class must have static methods) are faster than non-static.

Edit:
FxCop Performance rule description: "Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.

agnieszka
A: 

Here is a step by step process for getting to the singleton pattern using Test-Driven Development. I think it demonstrates pretty well, a situation in which a singleton can be quite useful, and how you might test your way towards this. This example is not currently thread safe. The double-lock trick is probably a good thing to add for thread safety. Let me know what you think! Testing a Singleton

Brandon Joyce
A: 

I'm not a great OO theorist, but from what I know, I think the only OO feature that static classes lack compared to Singletons is polymorphism. But if you don't need it, with a static class you can of course have inheritance ( not sure about interface implementation ) and data and function encapsulation.

The comment of Morendil, "The design style embodied in a static class is purely procedural" I may be wrong, but I disagree. In static methods you can access static members, which would be exactly the same as singleton methods accessing their single instance members.

Petruza