Design Patterns – Singleton Pattern – Part II

In this post, we will discuss the Singleton Design Pattern which is of Creational type design pattern. You can check out the introductory post about design patterns here.

Singleton Design Pattern

Singleton design pattern is the simplest design patterns in software engineering. As Singleton is a creational type of design pattern,  you can create an object using it, but only a single object.

In this design pattern, a single class creates an object but also makes sure that only a single object is created. This class provides a way to access the object, so as to avoid the need to instantiate the object.

Implementation of Singleton Design Pattern

In this design pattern, a class will have a private constructor and a static method to provide access to static members of the class instance. Most of the time singleton pattern is used in logger and configuration classes implementation.

package com.betterjavacode.designpatterns;

public class SingletonDemo 
{
    private static SingletonDemo demo;

    private SingletonDemo()
    {

    }

    public static SingletonDemo getInstance()
    {
      if (demo == null)
         demo = new SingletonDemo();
      return demo;
    }

    public void printSingletonDemo()
    {
       System.out.println(" This is a singleton design pattern demo ");
    }
}

Now any client code who wants to use SingletonDemo class can do this with SingletonDemo.getInstance(). The major advantage of the Singleton design pattern is it allows only one instance of an object.

Conclusion

In conclusion, among all design patterns, we started this series with a Singleton design pattern.

Download

The code for this post is available to download design patterns.

 

2 thoughts on “Design Patterns – Singleton Pattern – Part II

  1. Pingback: Design Pattern – Abstract Factory Pattern – Part IV | Code Complete

  2. Pingback: Design Pattern – Prototype Pattern – Part VI | Code Complete

Comments are closed.