The singleton pattern – what is it and what is it for?

Let's start by reviewing what the singleton pattern is, what it does, and when it should be used. Each pattern is a commonly accepted solution to a frequently occurring design problem, so what problem does the singleton pattern solve?

The singleton is a pattern that's used to restrict the number of class instantiations to exactly one. It should be considered when, by design, there should only be one object of a certain type in the entire system. A frequent criticism of the singleton is that it is a global variable in disguise, and global variables are bad. As a supposed downside of the singleton pattern itself, this critique misses the point: the pattern is a solution to the design challenge. You can argue that having a single global object in the entire system is a sign of bad design, but that is an argument against the problem itself, not against its particular solution. Assuming that the design need is legitimate, the singleton pattern is the canonical solution to address it.

We will, at first, set aside the question of whether good design can have global objects, which is to be revisited later. Let's start with a demonstration of a basic singleton.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.24.60