概念
分类
1、懒汉式
类加载的时候就创建实例
2、饿汉式
使用的时候才创建实例
当然还有其他的生成单例的方式,双重校验锁,枚举和静态内部类,文中会有介绍。
懒汉式
1) 示例1
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
2) 示例2
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
同步方法,线程安全,效率低,不推荐。
3) 示例3
public class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { singleton = new Singleton(); } } return singleton; } }
线程不安全,会产生多个实例,不可用。
饿汉式
无线程安全问题,不能延迟加载,影响系统性能。
4) 示例1
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
5) 示例2
public class Singleton { private static Singleton instance = null; static { instance = new Singleton(); } private Singleton (){} public static Singleton getInstance() { return instance; } }
6) 示例3
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;
}
}
双重校验锁,线程安全,推荐使用。
7) 示例4
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
静态内部类,线程安全,主动调用时才实例化,延迟加载效率高,推荐使用。
8) 示例5
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
注意事项
1、考虑多线程问题
2、单例类构造方法要设置为private类型禁止外界new创建
private Singleton() {}
3、如果类可序列化,考虑反序列化生成多个实例问题,解决方案如下
private Object readResolve() throws ObjectStreamException { // instead of the object we're on, return the class variable INSTANCE return INSTANCE; }
枚举类型,无线程安全问题,避免反序列华创建新的实例,很少使用。
使用场景
1、工具类对象
2、系统中只能存在一个实例的类
3、创建频繁或又耗时耗资源且又经常用到的对象
下面是单例模式在JDK的应用
另外,Spring 容器中的实例默认是单例饿汉式类型的,即容器启动时就实例化 bean 到容器中,当然也可以设置懒汉式 defalut-lazy-init="true"
为延迟实例化,用到时再实例化。
推荐去我的博客阅读更多:
1. Java JVM、集合、多线程、新特性系列教程
2. Spring MVC、Spring Boot、Spring Cloud 系列教程
3. Maven、Git、Eclipse、Intellij IDEA 系列工具教程
4. Java、后端、架构、阿里巴巴等大厂最新面试题
生活很美好,明天见~
原文
https://segmentfault.com/a/1190000022164924
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 单例模式的 8 种写法,整理非常全!