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.
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.
A Singleton candidate must satisfy three requirements:
controls concurrent access to a shared resource.
access to the resource will be requested from multiple, disparate parts of the system.
there can be only one object.
If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.
For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.
A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.
Reading configuration files that should only be read at startup time and encapsulating them in a Singleton.
Properties.Settings.Default
in .NET.
You use a singleton when you need to manage a shared resource. For instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource.
Or a database connection or a file manager etc.
Read only singletons storing some global state (user language, help filepath, application path) are reasonable. Be carefull of using singletons to control business logic - single almost always ends up being multiple
Managing a connection (or a pool of connections) to a database.
I would use it also to retrieve and store informations on external configuration files.
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 using Singletons, you should make sure that you're not accidentally concealing dependencies. Ideally, the singletons (like most static variables in an application) be set up during the execution of your initialization code for the application (static void Main() for C# executables, static void main() for java executables) and then passed in to all other classes that are instantiated which require it. This helps you maintain testability.
One of the ways you use a singleton is to cover an instance where there must be a single "broker" controlling access to a resource. Singletons are good in loggers because they broker access to, say, a file, which can only be written to exclusively. For something like logging, they provide a way of abstracting away the writes to something like a log file -- you could wrap a caching mechanism to your singleton, etc...
Also think of a situation where you have an application with many windows/threads/etc, but which needs a single point of communication. I once used one to control jobs that I wanted my application to launch. The singleton was responsible for serializing the jobs and displaying their status to any other part of the program which was interested. In this sort of scenario, you can look at a singleton as being sort of like a "server" class running inside your application... HTH
I think singleton use can be thought of as the same as the many-to-one relationship in databases. If you have many different parts of your code that need to work with a single instance of an object, that is where it makes sense to use singletons.
When you load a configuration Properties object, either from the database or a file, it helps to have it as a singleton; there's no reason to keep re-reading static data that won't change while the server is running.
A practical example of a singleton can be found in Test::Builder, the class which backs just about every modern Perl testing module. The Test::Builder singleton stores and brokers the state and history of the test process (historical test results, counts the number of tests run) as well as things like where the test output is going. These are all necessary to coordinate multiple testing modules, written by different authors, to work together in a single test script.
The history of Test::Builder's singleton is educational. Calling new()
always gives you the same object. First, all the data was stored as class variables with nothing in the object itself. This worked until I wanted to test Test::Builder with itself. Then I needed two Test::Builder objects, one setup as a dummy, to capture and test its behavior and output, and one to be the real test object. At that point Test::Builder was refactored into a real object. The singleton object was stored as class data, and new()
would always return it. create()
was added to make a fresh object and enable testing.
Currently, users are wanting to change some behaviors of Test::Builder in their own module, but leave others alone, while the test history remains in common across all testing modules. What's happening now is the monolithic Test::Builder object is being broken down into smaller pieces (history, output, format...) with a Test::Builder instance collecting them together. Now Test::Builder no longer has to be a singleton. Its components, like history, can be. This pushes the inflexible necessity of a singleton down a level. It gives more flexibility to the user to mix-and-match pieces. The smaller singleton objects can now just store data, with their containing objects deciding how to use it. It even allows a non-Test::Builder class to play along by using the Test::Builder history and output singletons.
Seems to be there's a push and pull between coordination of data and flexibility of behavior which can be mitigated by putting the singleton around just shared data with the smallest amount of behavior as possible to ensure data integrity.
Shared resources. Especially in PHP, a database class, a template class, and a global variable depot class. All have to be shared by all modules/classes that are being used throughout the code.
It's a true object usage -> the template class contains the page template that is being built, and it gets shaped, added, changed by modules that are adding to page output. It has to be kept as a single instance so that this can happen, and the same goes for databases. With a shared database singleton, all modules' classes can get access to queries and get them without having to rerun them.
A global variable depot singleton provides you a global, reliable, and easily usable variable depot. It tidies up your code a great lot. Imagine having all configuration values in an array in a singleton like:
$gb->config['hostname']
or having all language values in an array like:
$gb->lang['ENTER_USER']
In the end of running the code for the page, you get, say, a now mature:
$template
Singleton, a $gb
singleton that has the lang array for replacing into it, and all output loaded and ready. You just replace them into the keys that are now present in mature template object's page value, and then serve it out to user.
The great advantage of this is you can do ANY post-processing you like on anything. You can pipe all language values to google translate, or another translate service and get them back, and replace them into their places, translated, for example. or, you can replace in page structures, or, content strings, as you want.
First of all, let's distinguish between Single Object and Singleton. The latter is one of many possible implementations of the former. And the Single Object's problems are different from Singleton's problems. Single Objects are not inherently bad and sometimes are the only way to do things. In short:
Single Object - I need just one instance of an object in a program
Singleton - create a class with a static field. Add a static method returning this field. Lazily instantiate a field on the first call. Always return the same object.
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
As you can see, "Singleton" pattern in its canonical form is not very testing-friendly. This can be easily fixed, though: just make the Singleton implement an interface. Let's call it "Testable Singleton" :)
public class Singleton implements ISingleton {
private static Singleton instance;
private Singleton() {}
public static ISingleton instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Now we can mock Singleton because we use it via the interface. One of the claims is gone. Let's see if we can get rid of another claim - shared global state.
If we strip Singleton pattern down, at its core it's about lazy initialization:
public static ISingleton instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
That's the whole reason for it to exist. And that's the Single Object pattern. We take it away and put to the factory method, for instance:
public class SingletonFactory {
private static ISingleton instance;
// Knock-knock. Single Object here
public static ISingleton simpleSingleton() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
What's the difference with our Testable Singleton? There is none, because this is the essense of the Single Object pattern - it doesn't matter whether you implement it as a Singleton or a Factory Method or a Service Locator. You still have some shared global state. This can become a problem if it's accessed from multiple threads. You will have to make simpleSingleton()
synchronized and cope with all the multithreading issues.
One more time: whatever approach you choose, you will have to pay the Single Object price. Using a Dependency Injection container just shifts the complexity to the framework which will have to cope with Single Object's inherent issues.
Recap:
Most of people who mention Singleton mean Single Object One of the popular ways to implement it is the Singleton pattern It has its flaws that can be mitigated However, the most of Singleton's complexity roots in Single Object's complexity Regardless of how you instantiate your Single Object, it's still there, be it a Service Locator, a Factory Method or something else You can shift the complexity to a DI container which is (hopefully) well-tested Sometimes using the DI container is cumbersome - imagine injecting a LOGGER to every class
You can use Singleton when implementing the State pattern (in the manner shown in the GoF book). This is because the concrete State classes have no state of their own, and perform their actions in terms of a context class.
You can also make Abstract Factory a singleton.
setState()
responsible for deciding the state creation policy. It helps if your programming language supports templates or generics. Instead of Singleton, you could use the Monostate pattern, where instantiating a state object ends up reusing the same global/static state object. The syntax for changing the state could remain unchanged, as your users need not be aware that the instantiated state is a Monostate.
As everyone has said, a shared resource - specifically something that cannot handle concurrent access.
One specific example that I have seen, is a Lucene Search Index Writer.
You use the Singleton design pattern when you want to ensure that a class will have one instance, and that instance will have a global point of access to it.
So let's say that you have an application that requires to a database to process CRUD operations. Ideally you'd use the same connection object to the database to access the database and perform the CRUD operations.
Therefore, in order to ensure that the database class will have one object, and that same object will be used through out the application we implement the singleton design pattern.
Ensure that your constructor is private and that you provide a static method to provide access to the single object of the singleton class
I think if your app has multiple layers e.g presentation, domain and model. Singleton is a good candidate to be a part of cross cutting layer. And provide service to each layer in the system.
Essentially Singleton wraps a service for example like logging, analytics and provides it to other layers in the system.
And yes singleton needs to follow single responsibility principle.
I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.
In many ways, a singleton for handling CGI parameters would work similarly if you're only using one process per query (other mod_* methods don't do this, so it'd be bad there - thus the argument that says you shouldn't use singletons in the mod_cgi world in case you port to the mod_perl or whatever world).
It can be very pragmatic to configure specific infrastructure concerns as singletons or global variables. My favourite example of this is Dependency Injection frameworks that make use of singletons to act as a connection point to the framework.
In this case you are taking a dependency on the infrastructure to simplify using the library and avoid unneeded complexity.
So I'm reading up on the singleton pattern for school, and the professors curated a list of current opinions and best practices on the subject. There seems to be agreement on the idea that a singleton is okay to use if you build it such that it doesn't add anything to the code. If you make it so that singleton use can be toggled on and off with literally no side effects other than work load, then it's safe and desirable to use this design pattern.
Singleton pattern is the most pervasive pattern in the Spring containerization approach. If we look at that in terms of architectural primitives - they form a blackboard graph of objects, to which every thread can read and write. They do the dramatic act of synchronizing between multiple threads. The very reason why multiple threads need to synchronize is because there are always resources that underlie a computational program, over which contention might occur. Consider what is called a 'last seat problem'. A flight is being booked, but there are multiple ways to do it. For simplicity lets assume that the data about the flight occupancy is stored in a flat file rather than a database. Now, if there are two threads, each functionally different (i.e represented by different endpoints in the webapp) and let one of these threads A, be the thread which a prospective passenger uses to make a booking and the other one B is which a flight manager uses to close the booking - virtually closing the boarding door. Then, if these threads do not use singleton, the flight object would be detached from the real resource out-there, which we say not the actual aeroplane but the entry in the flat file. The A thread would have reference to an object, while the passenger is still fighting a dilemma whether to fly or not and then finally when he makes up his mind, the B thread would already have closed the door. But the object referenced by the A thread would still show one more seat to go. Now, cutting out the RDBMS due to our initial assumption, the system would write a ticket for the passenger and issue it to him eventhough the boarding is closed. Now, in a singleton implementation, the moment the theread B accesses the system, the universal object Flight is updated with status closed. Hence, if the passenger finally makes up his mind and clicks confirm, he would get an error right away. All this would not have been possible without the singleton. Hence, singleton allows you to stay close to the resources and avoids thread contention.
An example with code, perhaps.
Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):
http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html
Ed.
Success story sharing