51

When would a singleton actually be easier or better than a static class? It seems to me creating a singleton is just extra effort that's not actually needed, but I'm sure there is a good reason. Otherwise, they wouldn't be used, obviously.

7 Answers 7

36

One good reason for preferring a singleton over a static class (assuming you have no better patterns at your disposal ;) ), is swapping out one singleton instance with another.

For example, if I have a logging class like this:

public static class Logger {
    public static void Log(string s) { ... }
}

public class Client {
    public void DoSomething() {
        Logger.Log("DoSomething called");
    }
}

It works really well, but what if Logger writes things to a database, or writes output to the console. If you're writing tests, you probably don't want all those side-effects -- but since the log method is static, you can't do anything except.

Ok, so I want to hot-swap my Log method for testing. Go go gadget singleton!

public class Logger {
    private static Logger _instance;
    public static Logger Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Logger();
            return _instance;
        }
        set { _instance = value; }
    }
    protected Logger() { }
    public virtual void Log(string s) { ... }
}

public class Client {
    public void DoSomething() {
        Logger.Instance.Log("DoSomething called");
    }
}

So you can define a TestLogger : Logger with an empty Log method, then set an instance of your test logger to the singleton instance for tests. Presto! You can hotswap your logger implementation for tests or production without affecting client code.

11

Singletons are often preferred to global variables because:

  • They don't pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
  • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

Source

EDIT:

One cool use of the singleton is, when combined with the factory method, can be used to create the Flyweight pattern. This is when you create a new object, the Factory (instead of creating a new object) first checks to see a singleton of that object is already made, if it is, it just returns that object, if not, it creates a new singleton and returns that, keeping track of the singletons it creates. Flyweights work because of the immutability of the singleton.

2
  • 2
    Flyweight is more like a "multiton", not really a singleton.
    – BalusC
    Commented Jun 3, 2010 at 20:51
  • 3
    Static classes are lazy in many languages. They are not initialized until they are called.
    – PSsam
    Commented Jun 1, 2013 at 17:40
8
  1. A Singleton can implement interfaces, inherit from other classes
  2. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR (common language runtime) when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded and it will lead to potential class loader issues.
  3. Singleton class follow the Object Oriented Principles
  4. Singleton Objects stored on heap while static class stored in stack.
  5. Singleton Objects can have constructor while Static Class cannot.
  6. Singleton Objects can dispose but not static class
  7. Singleton Objects can clone but not with static class
4
  • Most of these benefits should be prefaced w/ "...when needed". Always prefer the less complex solution (regardless of degree, it's the habit). Actually static classes are allocated on the heap (not stack); they're still reference types and are "instantiated", just not by user code. Storage on the heap isn't necessarily an advantage anyway; it is more work to use (e.g. shared so requires concurrency mgt), and slower. OO doesn't preclude the use of static members. They're initialized lazily (on 1st use) in most languages. good notes here: dzone.com/articles/singleton-anti-pattern
    – galaxis
    Commented May 18, 2018 at 20:25
  • Thanks! This is exactly what i am looking for Commented Jul 19, 2020 at 17:12
  • 1
    To point 5: static constructors exist in C# and Java.
    – W0lfw00ds
    Commented May 25, 2023 at 7:29
  • Are you sure about point 4? In C#, both singleton objects and static classes are stored in the program's data segment, which is a separate area of memory from the stack and heap.
    – Mujan
    Commented Jul 8, 2023 at 18:28
7

Even though IMHO the singleton pattern is a rather overused pattern, it does sometimes offer benefits, such as:

  • The ability to use different kinds of objects (that inherit from the same base) as the instance (think data providers where one uses the filesystem and one an SQL database, for example)
  • Serializability. I haven't used a framework that can automatically serialize static classes.
  • Using less static fields. For some people this is more of an esthetic feature, but in some cases it has practical benefits.
6

Singletons always seemed a bit redundant to me. I prefer static classes, and if I need different behavior, I combine it with a dependency injection and a provider.. I don't know what pattern this is, or if it has a name, but it usually goes something like this:

public interface IFooProvider {
  Bar FooBar();
}

public static class Foo {
  public static readonly IFooProvider FooProvider { get; set; }
  public Bar FooBar() { return FooProvider.FooBar(); }
}

Then I just make sure to set the provider somewhere in my init method. It's easy enough to add lazy initialization if you want to by setting the default provider at class initialization. Best of all, it allows you to change the behavior while still getting the aesthetic of using static classes.

3

In many languages static classes lack useful features, like inheritance (and polymorphism more generally).

(Not that I'm advocating singletons.)

2

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

Also,you can use singletons with interfaces just like any other class.

Not the answer you're looking for? Browse other questions tagged or ask your own question.