当前位置:网站首页>单例模式
单例模式
2022-08-09 06:22:00 【考拉盖饭】
单例模式
单例模式分饿汉式和懒汉式
饿汉式:
在类加载时就完成了初始化,所以类加载比较慢,不过这个慢也是看实例对象的大小,一般的单例都不会存放大容量的内容,所以大部分在毫秒级别,但获取对象的速度快。
public class Hungry {
private Hungry(){
// 私有化构造器
}
private static Hungry HUNGRY = new Hungry(); // 饿汉式
// 对外提供获取对象的方法
public static Hungry getInstance() {
return HUNGRY;
}
}
懒汉式:
在类加载时不初始化,等到第一次被使用时才初始化,所以会有并发的可能存在。
1.双重检查懒汉式
public class Lazy {
private Lazy(){
// 私有化构造器
}
private volatile static Lazy lazy;
// 双重检查懒汉式,当然,这种方式可以被反射破坏,不过正常使用这一种就可以
public static Lazy getInstance() {
if (lazy==null){
synchronized (Lazy.class){
if(lazy==null){
lazy = new Lazy();
}
}
}
return lazy;
}
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Lazy instance = Lazy.getInstance();
Constructor<Lazy> declaredConstructor = Lazy.class.getDeclaredConstructor(new Class[]{
});
declaredConstructor.setAccessible(true);
Lazy lazy = declaredConstructor.newInstance();
System.out.println(instance);
System.out.println(lazy);
/*for (int i = 1; i <= 10; i++) { new Thread(()->{ Lazy.getInstance(); },String.valueOf(i)).start(); }*/
}
}
2.枚举懒汉式
// 因为枚举本身自动支持序列化机制,绝对防止多次实例化
public enum EnumSingle {
SINGLE;
public static EnumSingle getInstance(){
return SINGLE;
}
}
// 试图通过反射来破坏枚举的单例也是不成功的
class Test{
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
EnumSingle instance = EnumSingle.getInstance();
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
EnumSingle enumSingle = declaredConstructor.newInstance();
System.out.println(instance);
System.out.println(enumSingle);
}
}
边栏推荐
- 磁性核壳四氧化三铁颗粒负载金纳米星|磁性Fe3O4-POSS-COOH|超顺磁四氧化三铁聚多巴胺核壳结构纳米粒子
- phpstudy install flarum forum
- 工控设备的系统如何进行加固
- MYSQLg高级------批量插入百万级数据量
- Online tool for sorting multi-line strings
- MYSQL高级篇-----查询截取分析,锁机制,主从复制
- Getting started with kubernetes apparmor
- Deep Learning - Principles of Neural Networks 2
- 中英文说明书丨TRC D-阿卓糖(D-Altrose)
- 程序性能分析 —— 复杂度分析
猜你喜欢
随机推荐
tidb crash test
untiy countdown
如何操作数据库
[MySQL]二、进程的关系、MySQL密码破解、建表和建库相关命令
缓存技术使用
记一个 nest.js 路由匹配后面所有路径问题
Unity Gobang Game Design and Simple AI(3)
声母-字母查询工具-词语缩写查询在线工具
Fe3O4/SiO2 Composite Magnetic Nanoparticles Aminated on SiO2-NH2/Fe3O4 Surface (Qiyue Reagent)
正则表达式-判断字符串是否匹配“AABB”模式
Qt learning (3) - Qt module
金仓数据库能否设置事务自动提交
Domain name batch query online tool
直播源码开发,点击扫描跳转到扫码页面
二十四节气之立秋
【Feel】In the Unity Feel plugin, Camera cannot display CameraShake correctly
22 high mid term paper topics forecast
直播电商平台开发,点击查看更多显示所有内容
[R language] interaction test data
Invalid argument(s) appears when redis runs lua script