单例模式的多种实现方式
1.饿汉模式
public class Singleton { private static Singleton singleton = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return singleton; } }
2.懒汉模式
public class Singleton { private static Singleton singleton; private Singleton() {} synchronized public static Singleton getInstance(){ if(singleton!=null){ }else{ singleton = new Singleton(); } return singleton; } }
3. 双重校验锁
public class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance(){ if(singleton!=null){ }else{ synchronized (Singleton.class){ if(singleton==null){ Singleton = new Singleton(); } } } return Singleton; } }
4.静态内部类
public class Singleton { private static class SingletonHandle{ private static Singleton singleton = new Singleton(); } private Singleton(){} public static Singleton(){ return SingletonHandle.singleton; } }