JAVA单例模式的几种写法

/**
 * 单例模式懒汉式(双重检锁线程安全。JDK1.5之后)
 */
public class Singleton {

    private static volatile Singleton singleton = null;
    
    private Singleton(){}
    
    public static Singleton getInstance(){
        if(singleton == null) {
            synchronized(Singleton.class) {
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

/**
 * 单例模式(内部类写法)
 */
public class Singleton {
    
    private static class SingletonClass{
        public static final Singleton singleton = new Singleton();
    }
    
    public static Singleton getInstance(){
        return SingletonClass.singleton;
    }
}

/**
 * 单例模式饿汉式
 * @author Administrator
 *
 */
public class Singleton{
    private static Singleton singleton = new Singleton();
    
    public static synchronized Singleton getInstance(){
        return singleton;
    }
}

 

posted @ 2018-09-05 11:47  DreamPig丶  阅读(226)  评论(0编辑  收藏  举报