The singleton pattern
The singleton is easily the simplest of patterns, but it is also one of the most controversial. Many developers think it entirely unnecessary and that declaring a class as static performs the same function with less fuss. Although it is true that the singleton is widely overused when a static class would be the cleaner choice, there are certainly times when one is preferable to the other:
- Use a static class when you want a function performed on a variable you pass to it, for example, calculating the discount value on a price variable
- Use a singleton pattern when you want a complete object, but only one, and you want that object to be available to any part of the program, for example, an object representing the individual user currently logged into an app
The class diagram for the singleton is, as you would imagine, remarkably simple, as you can see here:
As the preceding diagram suggests, the following example will assume we only have one user logged into our app at...