构造单例的五种方法

package jzoffer;

/**
 * @Author: Hiram
 * @Date: 2019/02/21 0:32
 */
public class Singleton {
    private Singleton(){

    }
    /**第一种 饿汉式*/
    private static Singleton singleton = new Singleton();
    public static Singleton getInstance(){
        return singleton;
    }

    /**第二种 饿汉模式、变种*/
    private static Singleton singleton2;
    static {
        singleton2 = new Singleton();
    }
    public static Singleton getInstance2(){
        return singleton2;
    }

    /**第三种 懒汉、线程安全*/
    private static Singleton singleton3 = null;
    public static synchronized Singleton getInstance3(){
        if (singleton3 == null)
            singleton3 = new Singleton();
        return singleton3;
    }

    /**第四种 懒汉、线程安全、效率高*/
    private static Singleton singleton4 = null;
    public static Singleton getInstance4(){
        if (singleton4 == null)
            synchronized (Singleton.class){
                if (singleton4 == null)
                    singleton4 = new Singleton();
            }
        return singleton4;
    }

    /**第五种 推荐 静态内部类:java静态内部类都是在访问时才创建,延迟加载策略*/
    private static class SingletonInner{
        private static Singleton singleton5 = new Singleton();
    }
    public static Singleton getInstance5(){
        return SingletonInner.singleton5;
    }

    /*
    其实还可以通过序列化,反序列化实现(注意把获取单例的方法改为非静态,否则反序列化会得到不同类),这里时间有限,就不例举了
     */
}
posted @ 2019-02-21 00:50  hirampeng  阅读(407)  评论(0编辑  收藏  举报