단일 모드 (게으름뱅이 식 과 굶 주 린 사람 식)

11805 단어 디자인 모드
package com.jason.singleton1;

/**
 * @author jason
 * @Description:                       
 * @date 2018/2/2
 */
public class Singleton {

    //1.      
    private Singleton(){

    }
    //2.       
    private static  Singleton singleton = null;

    //3.        
    public static  Singleton getSingleton(){
        if(singleton == null){
            //      , new   sinleton
            //           ,       
            synchronized (Singleton.class) {
                singleton = new Singleton();
            }
        }
        return singleton;
    }
}
package com.jason.singleton1;

/**
 * @author jason
 * @Description:                     
 * @date 2018/2/2
 */
public class Singleton1 {
    //1:        
    private Singleton1(){

    }
    //2.             
    private static  Singleton1 singleton1 = new Singleton1();

    //3.            
    public static Singleton1 getSingleton1(){
        return singleton1;
    }
}
package com.jason.singleton1;

/**
 * @author jason
 * @Description:       
 * @date 2018/2/2
 */
public class Test {

    public static void main(String[] args) {
        //     
        Singleton1 s1 = Singleton1.getSingleton1();
        Singleton1 s2 = Singleton1.getSingleton1();

        //    true,            
        System.out.println(s1 == s2);


        //     
        Singleton singleton = Singleton.getSingleton();
        Singleton singleton1 = Singleton.getSingleton();

        //    true,           
        System.out.println(singleton == singleton1);
    }
}

좋은 웹페이지 즐겨찾기