Java设计模式七种写法
2024-10-07 00:42:47
懒汉模式-线程不安全
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉模式-线程安全
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
饿汉模式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){
}
public static Singleton getInstance() {
return instance;
}
}
饿汉模式-变种
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){
}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
双重校验锁
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
枚举
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
最新文章
- tornado 学习笔记9 Tornado web 框架---模板(template)功能分析
- ionic 界面数据缓存问题
- (转载)在Visual Studio 2015中使用Git
- Android WebView 开发教程
- asp.Net获取脚本传过来的参数的方法汇总
- js实现时钟
- stage simulator
- MongoDB 基础命令使用学习记录
- java 21-13 合并
- 微信新版支持读取iPhone M7/M8协处理器运动数据 与好友PK一下运动量吧
- zoj 1097 普吕弗序列
- Shell实现跳板机,为什么用跳板机
- .NET中如何使用反序列化JSON字符串/序列化泛型对象toJsonStr
- Python之路【第一篇】:Python前世今生
- bootstrap's plugin:sthe usage of carousel
- python+selenium自动化软件测试(第1章):环境搭建,你也可以直接用Anaconda!
- 推荐一款接口文档在线管理系统-MinDoc
- Git环境配置+VSCode中文乱码问题
- springmvc+mybatis+mysql 数据库插入中文是乱码
- MongoDB 分片集群技术