手写单例模式(六种)

1. 懒汉式(线程不安全)

public class Singleton {
    /**
     * 懒汉式(线程不安全)
     */
    private static Singleton singleton;
    private Singleton(){}
    public static Singleton getInstance(){
        if(singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

2. 懒汉式(线程安全)

public class Singleton {
    /**
     * 懒汉式(线程安全)
     */
    private static Singleton singleton;
    private Singleton(){}
    public static synchronized Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

3. 饿汉式(线程安全)

public class Singleton {
    /**
     * 饿汉式(线程安全)
     */
    private static Singleton singleton = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return singleton;
    }
}

4. 双重检查锁实现(线程安全)

public class Singleton {
    /**
     * 双重检查锁实现(线程安全)
     */
    private static volatile Singleton singleton;
    private Singleton(){}
    public static Singleton getInstance(){
        if(singleton == null){
            synchronized (Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

5. 静态内部类实现(线程安全)

public class Singleton {
    /**
     * 静态内部类实现(线程安全)
     */
    private Singleton(){}
    private static class SingletonHolder{
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance(){
        return SingletonHolder.INSTANCE;
    }
}

6. 枚举类实现(线程安全)

public enum Singleton{
    INSTANCE;
    public void doSomething(){

    }
}

参考链接:轻松手写单例模式的6种实现方式!再也不怕面试官问了!

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