标签:tin 内部类 style 效率比较 throw return ret obj 设计模式
单例模式是我们平时使用最多的一种设计模式。它的设计目的是为了保证一个类只有一个对象实例。单例模式的实现思路为:首先我们需要私有化类的构造器,然后创建一个该类对象的静态属性,对用户暴露一个静态方法来返回该类对象的实例。下面我来介绍一下实现单例模式的几种方式:
1.饿汉式:
public class Singleton { private static Singleton singleton = new Singleton(); private Singleton(){}; public static Singleton getInstance(){ return Singleton.singleton; } }
2.懒汉式(线程不安全的):
public class Singleton { private static Singleton singleton ; private Singleton(){}; public static Singleton getInstance(){ if(Singleton.singleton ==null){ Singleton.singleton = new Singleton(); } return Singleton.singleton; } }
3.懒汉式(线程安全的)
public class Singleton { private static Singleton singleton ; private Singleton(){}; public static Singleton getInstance(){ synchronized (Singleton.class) { if(Singleton.singleton ==null){ Singleton.singleton = new Singleton(); } } return Singleton.singleton; } }
4.双重检查式(使用volatile修饰为了多个线程之间可见以及防止指令重排)
public class Singleton { private static volatile Singleton singleton ; private Singleton(){}; public static Singleton getInstance(){ if(Singleton.singleton ==null){ synchronized (Singleton.class) { if(Singleton.singleton ==null){ Singleton.singleton = new Singleton(); } } } return Singleton.singleton; } }
5.静态代码块:
public class Singleton { private static Singleton singleton ; private Singleton(){}; static{ Singleton.singleton = new Singleton(); } public static Singleton getInstance(){ return Singleton.singleton; } }
6.静态内部类:
public class Singleton { private Singleton(){}; static class InnerStaticClass{ private static final Singleton singleton = new Singleton(); } public static Singleton getInstance(){ return InnerStaticClass.singleton; } }
7.枚举
public enum EnumSingleton { INSTANCE; public EnumSingleton getInstance(){ return INSTANCE; } }
8.容器式:
public class SingletonHolder{ private static Map<String,Object> map = new ConcurrentHashMap<String, Object>(); public static void put(String key,String className) throws ClassNotFoundException{ if(!map.containsKey(key)){ map.put(key,Class.forName(className)); } } public static Object get(String key){ return map.get(key); } }
总结:单例是在我们平时开发中经常使用的一种模式,建议使用静态内部类的方式创建单例效率比较高并且也是线程安全的。
static
标签:tin 内部类 style 效率比较 throw return ret obj 设计模式
原文地址:https://www.cnblogs.com/suyang-java/p/10331213.html