Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use singleton instead of static class?

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.

like image 236
Jouke van der Maas Avatar asked Jun 03 '10 20:06

Jouke van der Maas


People also ask

What is the reason to use a singleton instead of a class with only static members and never instantiate any object of that class?

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).

Why would you use singleton?

A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

When should I use singleton class?

It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn't have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.

What's the difference between a singleton class and a static class?

The singleton, like any other instance of a class, lives on the heap. To its advantage, a huge singleton object can be lazily loaded whenever required by the application. On the other hand, a static class encompasses static methods and statically bound variables at compile time and is allocated on the stack.


2 Answers

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.

like image 161
Juliet Avatar answered Sep 22 '22 09:09

Juliet


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.

like image 43
Ryan Hayes Avatar answered Sep 23 '22 09:09

Ryan Hayes