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.
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.
Reading configuration files that should only be read at startup time and encapsulating them in a Singleton.
1 - A comment on the first answer:
I don't agree with a static Logger class. this can be practical for an implementation, but it cannot be replaceable for unit testing. A static class cannot be replaced by a test double. If you don't unit test, you won't don't see the problem here.
2 - I try not to create a singleton by hand. I just create a simple object with constructors that allow me to inject collaborators into the object. If I needed a singleton, I'd use a dependency inyection framework (Spring.NET, Unity for .NET, Spring for Java), or some other.
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.
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.
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.
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.