Factsheet
language agnostic - Purpose of singletons in programming - Stack Overflow
What, when why Singleton design pattern?
Singleton Design Pattern: Managing Global States in Your Applications
Singleton where to avoid living
Videos
The main advantage of a singleton over a class consisting of statics is that you can later easily decide that you need in fact more than one instance, e.g. one per thread.
However, in practice the main purpose of singletons is to make people feel less bad about having global variables.
A practical example for a good use of a singleton: you have an app that uses an SQL database and you need a connection pool. The purpose of such a pool is to reuse DB connection, so you definitely want all clients to use the same pool. Thus, having it as a singleton is the correct design. But one day you need the app to connect to a second DB server, and realize that you cannot have connections to different servers in the same pool. Thus your "one instance overall" singleton becomes "one instance per DB server".
why you would wan't to
I wouldn't because singletons usually are a bad way to solve your problems. My recommendation to you is to avoid them completely.
The main reasons are:
- Singletons mostly represent global state (which is evil).
- Correct dependency injection becomes impossible.
I suggest you read the rest (including thorough explanations) in this Google employee's blog:
- Singletons are Pathological Liars
- Where Have All the Singletons Gone?
- Root Cause of Singletons
- Flaw: Brittle Global State & Singletons
I am reading about Singleton design pattern and I don't understand why we should use it, a lot of people will say, oh to create a single instance of that class in order to save resources, and it's fine I get it, then we should use it for every class? Because from my understating we use it only on classes that their data not change, se they upload it one time in the memory and share them across the code, am I right? At this point will be useless to instantiate multiple objects which return the same unchangeable data? Right?