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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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(); } } |
Implementing Singleton class with getInstance() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// Java program implementing Singleton class // with getInstance() method class Singleton { // static variable single_instance of type Singleton private static Singleton single_instance = null; // variable of type String public String s; // private constructor restricted to this class itself private Singleton() { s = "Hello I am a string part of Singleton class"; } // static method to create instance of Singleton class public static Singleton getInstance() { if (single_instance == null) single_instance = new Singleton(); return single_instance; } } // Driver Class class Main { public static void main(String args[]) { // instantiating Singleton class with variable x Singleton x = Singleton.getInstance(); // instantiating Singleton class with variable y Singleton y = Singleton.getInstance(); // instantiating Singleton class with variable z Singleton z = Singleton.getInstance(); // changing variable of instance x x.s = (x.s).toUpperCase(); System.out.println("String from x is " + x.s); System.out.println("String from y is " + y.s); System.out.println("String from z is " + z.s); System.out.println("\n"); // changing variable of instance z z.s = (z.s).toLowerCase(); System.out.println("String from x is " + x.s); System.out.println("String from y is " + y.s); System.out.println("String from z is " + z.s); } } |
Output:
1 2 3 4 5 6 7 8 |
String from x is HELLO I AM A STRING PART OF SINGLETON CLASS String from y is HELLO I AM A STRING PART OF SINGLETON CLASS String from z is HELLO I AM A STRING PART OF SINGLETON CLASS String from x is hello i am a string part of singleton class String from y is hello i am a string part of singleton class String from z is hello i am a string part of singleton class |