JAVA创建单例模式

1、懒汉式
public class Singleton {

    private Singleton(){}

    private static final Singleton singleton= new Singleton();


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

2、饿汉式

public class Singleton {

    private Singleton(){}

    private static volatile Singleton singleton= null;


    public static Singleton createInstance(){

        if(singleton == null){
            synchronized (Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
以上两种方式都可使用反射的方式打破单例,创建出新的对象
public class Main {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Constructor constructor = Singleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton singleton = constructor.newInstance();
        System.out.println(singleton);
        System.out.println(Singleton.createInstance());
    }
}

3、枚举单例

 public enum SingletonEnum{
    INSTANCE;
   private static class Singleton{

   }

    private Singleton singleton;
    SingletonEnum(){
        singleton = new Singleton();
    }

    public Singleton createInstance(){
         return SingletonEnum.INSTANCE.singleton;
     }
}

该种方式不可被反射创建

你可能感兴趣的:(java)