Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of singletons in programming

This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever created.

This sounds a lot like a static class to me. The main difference being that with a static class you don't / can't instance it, you just use it such as Math.pi(). With a singleton class, you would still need to do something like

singleton firstSingleton = new singleton(); firstSingleton.set_name("foo");  singleton secondSingleton = new singleton(); 

Correct me if i am wrong, but firstSingleton == secondSingleton right now, yes?

secondSingleston.set_name("bar"); firstSingleton.report_name(); // will output "bar" won't it? 

Please note, I am asking this language independently, more about the concept. So I am not worried about actually how to code such a class, but more why you would wan't to and what thing you would need to consider.

like image 236
thecoshman Avatar asked Mar 31 '10 07:03

thecoshman


People also ask

What is the purpose of singletons?

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system.

What are some of the benefits of singletons?

Primarily due to the fact that a singleton holds an instantiated object, whereas static classes do not, singletons have the following advantages over static classes: Singletons can implement interfaces. Singletons can be passed as parameters. Singletons can have their instances swapped out (such as for testing purposes ...


1 Answers

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

like image 68
Michael Borgwardt Avatar answered Oct 03 '22 18:10

Michael Borgwardt