1、饿汉式
public class HungryTest {
public static void main(String[] args) {
HungrySingleton hungrySingleton1 = HungrySingleton.getInstance();
HungrySingleton hungrySingleton2 = HungrySingleton.getInstance();
System.out.println(hungrySingleton1 == hungrySingleton2); //true 同一个对象
}
}
// 饿汉式写法
class HungrySingleton {
// 1.私有化构造器
private HungrySingleton() {
}
// 2.内部创建类的对象,对象为静态的
private static HungrySingleton instance = new HungrySingleton();
// 3.提供共用的静态的方法,返回类的对象
public static HungrySingleton getInstance() {
return instance;
}
}
2、懒汉式
public class LazyTest {
public static void main(String[] args) {
LazySingleton lazySingleton1 = LazySingleton.getInstance();
LazySingleton lazySingleton2 = LazySingleton.getInstance();
System.out.println(lazySingleton1 == lazySingleton2); //true 同一个对象
}
}
// 懒汉式写法
class LazySingleton {
// 1.私有化构造器
private LazySingleton() {
}
// 2.声明当前类的对象,没有初始化。对象为静态的
private static LazySingleton instance = null;
// 3.提供共用的静态的方法,返回类的对象
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
// 懒汉式写法:线程安全+效率高
class LazySingleton2 {
private LazySingleton2() {
}
private static LazySingleton2 instance = null;
public static LazySingleton2 getInstance() {
if (instance == null) {
synchronized (LazySingleton2.class) { // 因为是静态方法,不能使用this
if (instance == null) {
instance = new LazySingleton2();
}
}
}
return instance;
}