Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On design patterns: When should I use the singleton?

The glorified global variable - becomes a gloried global class. Some say breaking object-oriented design.

Give me scenarios, other than the good old logger where it makes sense to use the singleton.

like image 237
Setori Avatar asked Oct 23 '08 01:10

Setori


People also ask

When would you use the Singleton design pattern?

Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.

When should you not use a singleton?

Work-arounds typically break the "single instance" part of a singleton. Consider a situation where you have multiple projects relying on shared code in a NetworkManager class. Even if you want this NetworkManager to be global state, and single instance, you should be very skeptical about making it into a singleton.

What is the need for the Singleton pattern?

The purpose of the singleton class is to control object creation, limiting the number of objects to only one. The singleton allows only one entry point to create the new instance of the class.


1 Answers

On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.

One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project. If every class uses this logging class, dependency injection becomes cumbersome.

Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."

I'm sure there are other valid reasons as well. Alex Miller, in "Patterns I Hate", talks of service locators and client side UI's also being possibly "acceptable" choices.

Read more at Singleton I love you, but you're bringing me down.

like image 149
CodingWithoutComments Avatar answered Dec 09 '22 09:12

CodingWithoutComments