package com.jerry.java;
/**
* @author jerry_jy
* @create 2022-10-01 19:27
*/
public class SingletonTest {
// 单例设计模式之懒汉式(线程安全)
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);//true
}
}
class Singleton {
// 2.内部提供一个当前类Singleton的实例singleton
// 4.此实例也必须静态化static
private static Singleton singleton;
// 1.私有化构造器
private Singleton() {
}
// 3.提供公共的静态的方法getInstance,返回当前类的对象return singleton
public static Singleton getInstance() {
if (singleton == null) {
//synchronized同步监视器:每次只new 一个当前类的对象
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}