//懒汉式
public class Single {
// 私有的构造方法
private Single() {}
// 私有的静态单例
private static Single instance = null;
public static Single getInstance() {
//不存在才去new
if (instance == null) {
//存在多线程访问
synchronized (Single.class) {
if (instance == null) {
instance = new Single();
}
}
}
return instance;
}
}
//饿汉式
public class Single {
// 私有的构造方法
private Single() {
}
// 私有的静态单例
private static Single instance = new Single();
public static Single getInstance() {
return instance;
}
}
单例
最新推荐文章于 2024-01-05 10:46:13 发布