1、用到过的场景
- 需要一样的对象放入数组中
- 构建类的方式固定
2、饿汉模式(不要用)
package com.cc.eed.sin;
/**
* <p>单例模式 - 饿汉 (线程不安全)</p>
*
* @author CC
* @since 2023/10/12
*/
public class SingletonDemo2 {
private static final SingletonDemo2 INSTANCE = new SingletonDemo2();
private SingletonDemo2(){
}
public static SingletonDemo2 getInstance() {
return INSTANCE;
}
}
3、懒汉模式
- 推荐使用:双重验证 + 锁
package com.cc.eed.sin;
/**
* <p>单例模式 - 懒汉 (线程安全)</p>
* <li>双重验证 + 锁</li>
*
* @author CC
* @since 2023/10/12
*/
public class SingletonDemo {
private static SingletonDemo INSTANCE;
private SingletonDemo(){
}
public static SingletonDemo getInstance() {
if (INSTANCE == null) {
synchronized (SingletonDemo.class) {
if (INSTANCE == null) {
INSTANCE = new SingletonDemo();
}
}
}
return INSTANCE;
}
}
4、参考:
https://www.cnblogs.com/ladderx/p/16854962.html