You are on page 1of 2

https://www.journaldev.

com/1377/java-singleton-design-pattern-best-practices-
examples

https://www.geeksforgeeks.org/singleton-class-java/

Java Singleton Pattern


To implement a Singleton pattern, we have different approaches but all of them have
the following common concepts.

Private constructor to restrict instantiation of the class from other classes.


Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global
access point for outer world to get the instance of the singleton class.

Program: Write a singleton class.

Description:
Singleton class means you can create only one object for the given class. You can
create a singleton class by making its constructor as private, so that you can
restrict the creation of the object. Provide a static method to get instance of the
object, wherein you can handle the object creation inside the class only. In this
example we are creating object by using static block.

Code:

package com.java2novice.algos;

public class MySingleton {

private static MySingleton myObj;

static{
myObj = new MySingleton();
}

private MySingleton(){

public static MySingleton getInstance(){


return myObj;
}

public void testMe(){


System.out.println("Hey.... it is working!!!");
}
public static void main(String a[]){
MySingleton ms = getInstance();
ms.testMe();
}
}

You might also like