设计模式之-单例模式
1、是什么?
单例模式是一种常用的软件设计模式,它在一个类中只允许创建一个对象实例,并且提供一个全局访问点来访问该实例。
2、怎么玩?
单例模式需要满足三个条件:单例类只能有一个实例;单例类必须自己创建自己的唯一实例;单例类必须给所有其他对象提供这一实例。
(1) 懒汉式
package com.ly.singleton;
/**
* 单例模式-懒汉式
*
* @author ly (个人博客:https://www.cnblogs.com/ybbit)
* @date 2023-10-31 0:00
* @tags 喜欢就去努力的争取
*/
public class Person {
private String name;
private Integer age;
public static Person instance;
private Person() {
}
/**
* 在需要的时候再去创建
*
* @return 实例对象
*/
public static Person getInstance() {
if (instance != null) {
instance = new Person();
}
return instance;
}
}
(2) 饿汉式
package com.ly.singleton;
/**
* 单例模式-饿汉式
*
* @author ly (个人博客:https://www.cnblogs.com/ybbit)
* @date 2023-10-31 0:02
* @tags 喜欢就去努力的争取
*/
public class Person2 {
private String name;
private Integer age;
/**
* 上来就直接创建
*/
private static final Person2 PERSON = new Person2();
public static Person2 getInstance() {
return PERSON;
}
}
(3) 懒汉式的一些问题
package com.ly.singleton;
/**
* 单例模式-懒汉式
*
* @author ly (个人博客:https://www.cnblogs.com/ybbit)
* @date 2023-10-31 0:00
* @tags 喜欢就去努力的争取
*/
public class Person3 {
private String name;
private Integer age;
public static volatile Person3 instance;
private Person3() {
}
/**
* 静态方法
* 锁太大效率太低
*
* @return 实例对象
*/
public static synchronized Person3 getInstance1() {
if (instance != null) {
instance = new Person3();
}
return instance;
}
/**
* 双重检索+内存可见性
*
* @return
*/
public static Person3 getInstance2() {
if (instance != null) {
synchronized (Person3.class) {
if (instance != null) {
instance = new Person3();
}
}
}
return instance;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2022-11-28 整合SpringBoot + Dubbo + Nacos 出现 Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass