tags:

views:

455

answers:

10

Pretty straight forward question.

What is a Singleton and when should I use it?

+15  A: 

What it is: A class for which there is just one, persistent instance across the lifetime of an application. See Singleton Pattern.

When you should use it: As little as possible. Only when you are absolutely certain that you need it. I'm reluctant to say "never", but there is usually a better alternative, such as DI or simply a static class.

Aaronaught
I'm not sure that a static class is a better alternative than a singleton... it really depends on the situation and language.
marcgg
@marcgg, it is not *always* a better alternative, but I have seen singleton implementations with no private data or state, which means that they would have been better off as static classes.
Aaronaught
Static classes don't behave in the same way as a singleton, a singleton can be passed into methods as a parameter whereas a static class can not.
TabbyCool
An example of a singleton being better would be a lazy loaded class, or one where initialization depended on another portion of the program. But unless you need control over the exact time of initialization, a static class handles most of the difficulties, such as synchronization, for you.
Guvante
Aggree with marcgg - I don't see a static class as a good alternative to singletons, because you still have the problem of supplying a substitute, e.g. during testing of a component that depends on this class. But I also see different uses, a static class would typically be used for independent utility functions that are independent of state, where a singleton is an actual class instance, and it would typically store a state. I completely agree to use DI instead, and then tell your DI container that you want it to only use a single instance of that class.
Pete
I should start adding a nitpicker's corner à la Chen. Note the words "usually" and "such as" in the second paragraph. ;) @Pete - some people actually use singletons to implement stateless utility functions, this was what I was getting at and advising against.
Aaronaught
Back to this same old religious debate... Who cares!
ChaosPandion
I downvoted this answer because it gives me no information on when to use it. "Only when you need it" doesn't really give me any information at all for someone that's new to singletons.
Sergio Tapia
@John McClane: I fail to see how the answer you accepted gives any more information than that.
Aaronaught
@Pete: I am sure this is a dumb question but what is DI? "I completely agree to use DI instead, and then tell your DI container that you want it to only use a single instance of that class."
Adkins
@Adkins: DI stands for Dependency Injection, which is when any class dependencies are passed in through (usually) a constructor or public property. DI alone doesn't solve the "distance" problem, but it is usually implemented alongside an Inversion-of-Control (IoC) container that knows how to automatically initialize any dependencies. So if you are creating a Singleton to solve the "X doesn't know how to find/talk to Y" problem, a combination of DI and IoC can solve the same problem with looser coupling.
Aaronaught
Makes sense. Thanks for taking the time to explain!
Adkins
+6  A: 

A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.

There is a C# implementation here covering most of what you need to know - including some good advice regarding thread safety.

To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.

Daniel May
A: 

Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern

I don't know C#, but it's actually the same thing in all languages, only implementation differs.

You should generally avoid singleton when it's possible, but in some situations it's very convenient.

Sorry for my English ;)

radex
+10  A: 

http://www.yoda.arachsys.com/csharp/singleton.html

NotDan
This is where we got our implementation from :-)
TabbyCool
A: 

Singleton is a design pattern.

klausbyskov
A: 

It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

You should use it if you want a class that can only be instanciated once.

marcgg
A: 

A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.

BFree
A: 

Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.

TabbyCool
A: 

You asked for C#. Trivial example:


public class Singleton
{
  private Singleton()
  {
    // Prevent outside instantiation
  }

  private static Singleton _singleton;

  public static Singleton GetSingleton()
  {
    if ( _singleton == null )
    {
      _singleton = new Singleton();
    }
    return _singleton;
  }
}
Chris Simmons
A: 

Everybody said about singleton,fair enough.Google says Singletons are Pathological Liars

Srinivas Reddy Thatiparthy
In an extreme, they are the global variables with a new name. And to help that, .net 4.0 will bring back the memory mapped files... now you can use global memory across all of your applications, very nice [sarcasm]!
Padu Merloti