单例模式

1、饿汉式

public class SingleObject{

//创建SingleObject 的一个对象

private static SingleObject instance = new SingleObject();

private SingleObject(){}

public static SingleObject getInstance(){

return instance;

}

}

2、懒汉式,线程不安全

public class  SingleObject{

private static SingleObject  instace= null;

private  SingleObject(){}

public static SingleObject  getInstance(){

if(instance == null){

instance = new SingleObject();

}

return instance;

}

}

3、懒汉式、线程安全

public class SingleObject{

private static SingleObjct instance;

private SingleObject(){}

public static synchronized  SingleObject  getInstance(){

if(instance == null){

instance == new  SingleObject()

}

return instance;

}

}

4、懒汉式双检锁/双重校验锁(DCL double-checked locking)、线程安全

public class  SingleObject{

private static volatile SingleObject instance;

private SingleObject(){}

public static SingleObject getInstance(){

synchronize(SingleObject.class){

if(instance == null){

instance= new  SingleObject();

}

return instance;

}

}

}

5、登记式/静态内部类

public class SingleObject{

private static class SingletonHolder { 

    private static final Singleton INSTANCE = new Singleton(); 

    } 

private SingleObject(){}

public static final SingleObject getInstance(){

return SingletonHolder.INSTANCE ;

}

}

}

6、枚举实现单例

publicclass EnumSingleton{

    private EnumSingleton(){}

    public static EnumSingleton getInstance(){

        return Singleton.INSTANCE.getInstance();

    }


    private static enum Singleton{

        INSTANCE;

        private EnumSingleton singleton;

        //JVM会保证此方法绝对只调用一次

      private Singleton(){

            singleton =new EnumSingleton();

        }

        public EnumSingleton getInstance(){

            return singleton;

        }

    }

}

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