单例模式

一、定义

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

二、实现

  1. 懒汉模式
package cn.wxz1997.concurrency.singleton;

/**
 * @Description: 懒汉模式(双重检测)
 * @Author: wxz1997
 * @Date 18-6-11下午6:02
 */
public class Singleton {

    /**
     * 若不加volatile修饰,由于jvm和cpu指令重排,无法保障可见性
     */
    private static volatile Singleton singleton = null;

    private Singleton(){

    }

    /**
     * 双重检测机制减小了同步的开销
     * @return
     */
    public static Singleton getInstance(){
        if (null == singleton){
            synchronized (Singleton.class){
                if (null == singleton){
                    singleton = new Singleton();
                }
            }
        }


        return singleton;
    }
}

  1. 饿汉模式
package cn.wxz1997.concurrency.singleton;

/**
 * @Description: 饿汉模式,在类装载时进行创建
 * @Author: wxz1997
 * @Date 18-6-11下午6:02
 */
public class Singleton {
    
    private static Singleton singleton = new Singleton();

    private Singleton(){
    }

    public static Singleton getInstance(){
        return singleton;
    }
}

  1. 枚举模式(推荐)
package cn.wxz1997.concurrency.singleton;

/**
 * @Description: 枚举模式
 * @Author: wxz1997
 * @Date 18-6-11下午6:02
 */
public class Singleton {
    

    private Singleton(){

    }

    public static Singleton getInstance(){
        return SingletonEnum.INSTANCE.getInstance();
    }

    private enum SingletonEnum {
        INSTANCE;
        private Singleton singleton;
        
        //jvm保证这个方法绝对只调用一次
        SingletonEnum(){
            singleton = new Singleton();
        }

        public Singleton getInstance() {
            return singleton;
        }
    }
}

  1. 静态内部类实现
package cn.wxz1997.concurrency.singleton;

/**
 * @Description: 静态内部类
 * @Author: wxz1997
 * @Date 18-6-11下午6:02
 */
public class Singleton {  
    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){
    }  
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE;  
    }  
}   

你可能感兴趣的:(单例模式)