Java设计模式之单例

/**
 * 单例!!!!!!!!!!!!!!!!!!!
 */
public class SingletonTest {
    private static SingletonTest instance = null;
    private SingletonTest(){

    }
    private  static  synchronized  void syncInit(){
        if(instance == null){
            instance = new SingletonTest();
            System.out.println("实例创建成功");
        }
    }
    public static SingletonTest getInstance(){
        if(instance == null){
            syncInit();
        }
        return instance;
    }

}
public class Test {
    public static void main(String[] args){
         SingletonTest singleton =  SingletonTest.getInstance();
         SingletonTest singleton1 = SingletonTest.getInstance();
    }
}

运行结果:

即只会创建一次实例!!!!!

 

posted @ 2017-07-21 18:51  AlexanderTheGreat  阅读(83)  评论(0编辑  收藏  举报