单例模式定义:确保一个类只有一个实例,并且自行实例化。
第一种(懒汉,线程不安全):
public class Singleton1 {
private static Singleton1 instance;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
}
第二种(懒汉,线程安全):
public class Singleton2 {
private static Singleton2 instance;
private Singleton2() {
}
public static synchronized Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
}
第三种(饿汉):
public class Singleton3 {
private static Singleton3 instance = new Singleton3();
private Singleton3() {
}
public static Singleton3 getInstance() {
return instance;
}
}
还有好几种方式先写最常见的三种。

本文深入解析了单例模式的三种实现方式:懒汉式(线程不安全)、懒汉式(线程安全)及饿汉式。每种方式都有其特点和适用场景,通过代码示例详细展示了如何确保一个类只有一个实例。
1007

被折叠的 条评论
为什么被折叠?



