Singleton instantiation

前端 未结 10 1620
我寻月下人不归
我寻月下人不归 2020-12-05 05:40

Below show is the creation on the singleton object.

public class Map_en_US extends mapTree {

    private static Map_en_US m_instance;

    private Map_en_US         


        
10条回答
  •  星月不相逢
    2020-12-05 05:52

        // 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());
    
            }
        }
    
    -------------------------------- OUT PUT -------------------------------------
    private constructor
    obj1  1169863946
    obj2  1169863946
    obj3  1169863946
    obj4  1169863946
    obj5  1169863946
    

提交回复
热议问题