Java Design Pattern – Singleton Pattern

Singleton Pattern is a design pattern which you often meet in almost applications. Singleton Pattern provides a way to instantiate only one instance in an application context.

The tutorial introduces the design of Singleton Design Pattern and give many ways to create a Singleton Pattern in your application.

I. Technology

– Java 8
– Eclipse: Version: Mars.2 Release (4.5.2)

II. Overview for Java – Singleton Pattern

Technical for creating Single Pattern:
– Create a private static variable of Singleton class. This is the only Instance of Singleton Class.
– Create private constructor for making sure outer class can NOT instantiate object form Singleton Class.
– Create a global method for get Singleton Instance.
java design pattern singleton pattern

Project Structure:
java design pattern project

III. Practices
1. Create a Singleton Class

2. Create Main class

3. Run & Result

Message from Main Class

Conclusion: singleton and newSingletonPointer is the same instance.

IV. How many ways to implement Singleton Pattern
1. Eager Singleton Pattern

The Eager Singleton pattern is simple way, the Singleton Instance will be created at the class loading time.
Disadvantage is that the instance is created but application maybe NOT use it right after creating time.

2. Static Block Singleton Implementation

The Static Block Singleton Implementation is same Eager Singleton Implementation, Instance is created at the Class loading time.

3. Lazy Singleton Implementation

Lazy Singleton Implementation will create Singleton Instance at the first time of Client call.

4. Thread Safe Singleton Pattern

The lazy singleton implementation does NOT adapt with multi-threading programming environment. So thread safe Singleton implementation will help us:

With implementation above, the synchronized lock is always checked, it makes down up performance. Double Checking Implementation below will resolve the problem.

5. Bill Pugh Singleton Pattern

Prior 5, Java memory model has lots of issues when having too many threads trying to get Instance, so Bill Pugh gives a new approach:

6. Enum Singleton Pattern

Java Reflection to destroy Singleton Pattern as Example:

instanceOne.hashCode() is difference instanceTwo.hashCode() because they are two difference instances. Java Reflection is a powerful tool used by many framework as: Spring Framework, Hibernate Framework.

So, to overcome problems above, Enum Singleton Implementation is a good solution:

V. Sourcecode

java singleton pattern

By grokonez | October 14, 2016.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

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