Singleton Design Pattern

If we would ever speak, what a design pattern is, that answer would be that a well described solution to a common software problem.

One of them is about which we will discussing is “Singleton”. Singleton pattern lies under “Creational design pattern” group. Here is the list of this group.

Creational Design Patterns

  • Singleton Pattern
  • Factory Pattern
  • Abstract Factory Pattern
  • Builder Pattern
  • Prototype Pattern

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java virtual machine.

Implementation

  • Make constructor as private
  • Write a static method that has return type of object this singleton class. The concept of Lazy Initialization is used to write this static method.
package com.denizkaradal.singleton;

public class Singleton {

    private static Singleton instance;
    
    private Singleton (){}
    
    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton ();
        }
        return instance;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: