单例模式
最常用的单例模式,经常在项目中见,梳理后发现各种各样的单例,索性梳理一下。
- 自己创建自己,提供了访问其唯一对象的方式,可以直接访问,不需要实例化对象。
- 私有构造
自己创建唯一实例
1.懒汉式
- 非线程安全
- lazy loading
- 不标准,不常用
1 2 3 4 5 6 7 8 9 10 11 12
| public class UserModel{ private static UserModel instance; private UserModel(){ } public static UserModel getInstance(){ if(instance == null){ instance = new UserModel; } return instance; } }
|
- 2.懒汉式
- 线程安全
- lazy loading
- synchronized 加锁影响效率
1 2 3 4 5 6 7 8 9 10 11 12
| public class UserModel{ private static UserModel instance; private UserModel(){ } public static synchronized UserModel getInstance(){ if(instance == null){ instance = new UserModel; } return instance; } }
|
- 3.饿汉式
- 线程安全
- 非lazy loading
- 非加锁,效率高
1 2 3 4 5 6 7 8
| public class UserModel{ private static UserModel instance = new UserModel; private UserModel(){} public static UserModel getInstance{ return instance; } }
|
- 4.双重锁校验
- 线程安全
- lazy loading
- 双锁机制,保持高性能
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class UserModel{ private volatile static UserModel instance; private UserModel(){} public static UserModel getInstance{ if(instance == null){ synchronized(UserModel.class){ if(instance == null){ instance = new UserModel(); } } } return instance; } }
|
1 2 3 4 5 6 7 8 9
| public class UserModel{ private static class Hodler{ private static final UserModel INSTANCE = new UserModel(); } private UserModel(){} public static final UserModel getInstance(){ return Hodler.INSTANCE; } }
|
总结