Design pattern Singleton, in a nutshell
It’s important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company.
There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Where I can use this pattern? [5,6]
- Hardware interface access,
- Configuration file,
- Controls concurrent access to a shared resource,
- Access to the resource will be requested from multiple, disparate parts of the system,
- Storing some global state (user language, help filepath, application path),
- Managing a connection (or a pool of connections) to a database.
In Spring the Singleton pattern could be easily used, just adding the annotation @ scope(“singleton”). But sometimes the Singleton doesn’t fit the requirements and the @ scope(“prototype”) should be used instead.
In order to check if the Singleton is applied, the code below does it. The test is repeated 3 times and only one instance of the class above should be created. After the execution, there is a verification on method testIt (bad name) I know 😥. To this test fails, only change the scope to “prototype”.
Now is Quarkus time 😍. In Quarkus, using the annotation @Singleton, yes a good name from Java EE, is used to declare that the class is a Singleton. As I said before if your requirements don’t fit in this pattern, use the annotation @Dependent to have other behavior.
The Singleton test for Quarkus follows the same approach as Spring, a repeated test, and then a test to check how many classes were used.
Now is time to code our Singleton. Is important to decide when creating the class and also don’t forget to use the synchronized reserved word on method declaration to avoid some pitfalls. I’m not cover all pitfalls, check the reference article number 4, in the References section.
Below, the Singleton structure, with a private constructor, a static method to return the instance, and one class behavior, in this case, count tasks. Remember, no one is able to execute two tasks at the same time, the humans are single task, as Singleton is.
As before, was used the repeated tests to prove how many instances were created.
Enum also could be used as a Singleton class. Behind the scenes the enum is converted into a class then has the same effect of using a class. Take a look on the enum and the test.
Test based on enum, to test if it’s a singleton.
The complete code is available on my GitHub.
1 — Cover image