单例模式

饿汉式


public class Singleton{
    private static volatile Singleton instance = new Singleton();
    
    private Singleton(){}
    
    public static Singleton getInstance() {
        return instance;
    }
}

懒汉式

public class Singleton{
   private static  Singleton instance;
   
   private Singleton(){}
   
   public static Singleton getInstance() {
       if(instance == null){
             intance = new Singleton():
       }
       return instance;
   }
}

双重检测

public class Singleton {
    private static volatile Singleton instance = null;

    private Singleton() {
    }

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

静态内部类

class Singleton{
    private static class SingletonDemo{
        private final static Singleton INSTANCE = new Singleton();
    }
    private Singleton(){}
    
    private static final Singleton getInstance() {
        return SingletonDemo.INSTANCE;
    }
}


枚举类

public enum Singleton{
INSTANCE;
public void instance(){}
}

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