1

I was searching for example of singleton design pattern implementation (double checked locking, enum, etc.) in java source code or other standard libraries. I wanted to check which approach/approaches is being taken by commonly used libraries. Please suggest some classes/libraries which implement the singleton design pattern.

bhanu
  • 149
  • 1
  • 1
  • 4
  • 1
    Singleton is an anti pattern designed to explicitly share mutable global state. If you find singletons in standard libraries, that's likely a mistake or old code. Better methods of sharing dependencies across different areas of code like using dependency injection and IoC (DiC) containers are a lot more common today. There are very few _actual_ use cases for Singletons. Related http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – Benjamin Gruenbaum Oct 22 '13 at 20:35

1 Answers1

1

// Best way to implement the singleton class in java
package com.vsspl.test1;

class STest {

    private static STest ob= null;
    private  STest(){
        System.out.println("private constructor");
    }

    public static STest  create(){

        if(ob==null)
            ob = new STest();
        return ob;
    }

    public  Object  clone(){
        STest   obb = create();
        return obb;
    }
}

public class SingletonTest {
    public static void main(String[] args)  {
        STest  ob1 = STest.create();
        STest  ob2 = STest.create();
        STest  ob3 = STest.create();

        System.out.println("obj1  " +  ob1.hashCode());
        System.out.println("obj2  " +  ob2.hashCode());
        System.out.println("obj3  " +  ob3.hashCode());


        STest  ob4 = (STest) ob3.clone();
        STest  ob5 = (STest) ob2.clone();
        System.out.println("obj4  " +  ob4.hashCode());
        System.out.println("obj5  " +  ob5.hashCode());

    }
}