单例模式:保证一个类有且仅有一个实例. 通过定义我们可知它是创建型的一种, 也是比较简单的一种
单例模式的使用场景: 频繁的进行创建和销毁的对象、创建对象时消耗过多或者消费资源过多,但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象.
下面主要分析一下单例模式的六种写法, 以及优缺点!
饿汉式(静态常量)
懒汉式(线程不安全)
懒汉式(线程安全)
双重检查
静态内部类
枚举
----------------------------------------------------------------------------------------------------------------------
代码
01
02
03
04
05
06
07
08
09
10
|
//饿汉式(静态常量) class Singleton { // 构造器私有 外部不能实例化 private Singleton() { } private final static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } } |
----------------------------------------------------------------------------------------------------------------------
代码
01
02
03
04
05
06
07
08
09
10
11
|
//懒汉式 class Singleton{ private static Singleton instance; private Singleton(){} public static Singleton getInstance(){ if (instance == null ){ instance = new Singleton(); } return instance; } } |
优点
缺点
----------------------------------------------------------------------------------------------------------------------
代码
01
02
03
04
05
06
07
08
09
10
11
|
//懒汉式(线程安全,同步方法) class Singleton{ private static Singleton instance; private Singleton(){} public static synchronized Singleton getInstance(){ if (instance == null ){ instance = new Singleton(); } return instance; } } |
优点
缺点
----------------------------------------------------------------------------------------------------------------------
代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
|
//双重检查(线程安全 实现了懒加载 同时保证了效率) class Singleton { private static volatile Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null ) { synchronized (Singleton. class ) { if (instance == null ) { instance = new Singleton(); } } } return instance; } } |
优点
----------------------------------------------------------------------------------------------------------------------
代码
01
02
03
04
05
06
07
08
09
10
|
//静态内部类 class Singleton{ private Singleton(){} private static class SingletonInstance{ private static final Singleton INSTANCE= new Singleton(); } public static synchronized Singleton getInstance(){ return SingletonInstance.INSTANCE; } } |
优点
----------------------------------------------------------------------------------------------------------------------
代码
01
02
03
04
05
06
07
08
09
10
11
12
|
enum Singleton{ INSTANCE; test t; private Singleton(){ t = new test(); } public test getTest(){ return t; } } class test{ } |
优点
解决了线程安全, 而且泛能防止反序列化重新创建新的对象
起到了lazy loading(懒加载)的效果
在实际开发中, 建议使用
设计模式真的是前辈们总结出来的精髓, 代表了最佳的实践, 还是需要继续的深入学习和理解里面的奥妙.
转自https://blog.csdn.net/ywq1016243402/article/details/103943659
原文:https://www.cnblogs.com/zhuxiaopijingjing/p/12258474.html