Design pattern Singleton, in a nutshell

Design Pattern Singleton

Motivation

Applicability

Where I can use this pattern? [5,6]

  1. Hardware interface access,
  2. Logger,
  3. Configuration file,
  4. Cache,
  5. Controls concurrent access to a shared resource,
  6. Access to the resource will be requested from multiple, disparate parts of the system,
  7. Storing some global state (user language, help filepath, application path),
  8. Managing a connection (or a pool of connections) to a database.

Examples

Spring

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.

Spring Singleton
Spring Singleton Test
Test result executed on IntelliJ

Quarkus/Java EE

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.

Quarkus Singleton
Quarkus Singleton Test
Test result executed on IntelliJ

Hands on

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.

Singleton
Singleton Test
Test result executed on IntelliJ

Using enum

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.

Enum singleton
Enum Singleton Test
Test execution

Code

The complete code is available on my GitHub.

References

1 — Cover image

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luiz Gustavo De O. Costa

Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices