Java Design Patterns – Singleton Pattern

Singleton pattern has very simple code structure and is easy to learn. The main problem with this design pattern is to know how to use it properly.

In this post, you can find:

  • example situation when to use Singleton design pattern
  • Singleton pattern code structure in Java
  • example how to use Singleton pattern

People use Singleton pattern in many situations and not every time this is correct. Singleton design pattern is used when you have a class that can have only one instance. To create the instance of this class we wouldn’t use a new keyword instead of we will use the method from this class named getInstance().

To prevent for overusing this pattern you should achieve one of this three condition: if you

  • can’t assign ownership of the single instance
  • need to use lazy initialization
  • can’t reach global access in another way

Singleton pattern example in Java

In this post, the example code is very simple. We would have Singleton class and we will get the instance of this class. After we would call the method on the class object that would display Hello World message to the console.

Singleton class

That’s the core of the Singleton pattern. The class is final. We have the variable named instance that is the instance of Singleton class. Variable is static and have the volatile keyword. That’s mean that Java would store this variable in the main memory, not in CPU cache. We want this to have multithread access to the Singleton instance. Remeber that this is the only one instance of this class that will be used in all threads of our code. Next, we have getInstance() method. This method checks if an instance of Singleton was created if not method create the new instance. In the end, return Singleton instance. The last method of the class is sayHello() that would display a message to console.

How to use Singleton Pattern?

Look at Client class:

Console output:

Singleton console output

Singleton is very easy to use. Only what we have to do is get the instance of Singleton class. Now, we have the class object and we can use method sayHello().

You can find the code used in this article on my GitHub: Singleton Pattern

The hardest thing in learning Singleton pattern is knowing when to use it correctly. Overusing of Singleton pattern is very frequent activity. Look at your code and think when you can use it and if it is the best option in that situation.
Good luck!

Want more? Look at my others post about Design Patterns


  1. Jan123 said:

    Gdzie są nowe posty ? :((((((((

    May 6, 2018

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.