单例模式即一个 JVM 内存中只存在一个类的对象实例。java
类加载的时候就建立实例面试
使用的时候才建立实例后端
固然还有其余的生成单例的方式,双重校验锁,枚举和静态内部类,文中会有介绍。安全
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
线程不安全,不可用。多线程
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
同步方法,线程安全,效率低,不推荐。架构
public class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { singleton = new Singleton(); } } return singleton; } }
线程不安全,会产生多个实例,不可用。工具
无线程安全问题,不能延迟加载,影响系统性能。性能
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
public class Singleton { private static Singleton instance = null; static { instance = new Singleton(); } private Singleton (){} public static Singleton getInstance() { return instance; } }
public class Singleton { private static volatile Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
双重校验锁,线程安全,推荐使用。spa
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
静态内部类,线程安全,主动调用时才实例化,延迟加载效率高,推荐使用。线程
public enum Singleton { INSTANCE; public void whateverMethod() { } }
一、考虑多线程问题
二、单例类构造方法要设置为private类型禁止外界new建立
private Singleton() {}
三、若是类可序列化,考虑反序列化生成多个实例问题,解决方案以下
private Object readResolve() throws ObjectStreamException { // instead of the object we're on, return the class variable INSTANCE return INSTANCE; }
枚举类型,无线程安全问题,避免反序列华建立新的实例,不多使用。
一、工具类对象
二、系统中只能存在一个实例的类
三、建立频繁或又耗时耗资源且又常常用到的对象
下面是单例模式在JDK的应用
另外,Spring 容器中的实例默认是单例饿汉式类型的,即容器启动时就实例化 bean 到容器中,固然也能够设置懒汉式 defalut-lazy-init="true"
为延迟实例化,用到时再实例化。
推荐去个人博客阅读更多:
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
生活很美好,明天见~