1 单例模式
JVM提供全局唯一的对象,实例化一次,由类自身进行实例化。
2 实现方式
2.1 懒加载
package designpattern.singleton;
/**
* @description 单例:懒加载
* @author xindaqi
* @since 2021-02-10 15:24:43
*/
public class LazyLoading {
private static LazyLoading instance;
private LazyLoading() {}
private static LazyLoading getInstance() {
if(instance == null) {
instance = new LazyLoading();
}
return instance;
}
}
2.2 预加载
package designpattern.singleton;
/**
* @description 单例模式:预加载
* @author xindaqi
* @since 2021-02-10 17:04:04
*/
public class Preloading {
private static Preloading instance = new Preloading();
private Preloading() {}
private Preloading getInstance() {
return instance;
}
}
2.3 双检锁
package designpattern.singleton;
/**
* @description 单例模式:双检锁
* @author xindaqi
* @since 2021-02-10 17:54:03
*/
public class DoubleCheckLocking {
private volatile static DoubleCheckLocking instance;
private DoubleCheckLocking() {}
public static DoubleCheckLocking getInstance() {
if(null == instance) {
synchronized(DoubleCheckLocking.class) {
if(null == instance) {
instance = new DoubleCheckLocking();
}
}
}
return instance;
}
}
2.4 内部静态类
package designpattern.singleton;
/**
* @description 单例模式:静态内部类
* @author xindaqi
* @since 2021-02-10 20:02:51
*/
public class StaticInside {
private static class StaticInsideHandler {
private static final StaticInside INSTANCE = new StaticInside();
}
private StaticInside() {}
public static final StaticInside getInstance() {
return StaticInsideHandler.INSTANCE;
}
}
2.5 枚举
package designpattern.singleton;
/**
* @description 单例模式:枚举
* @author xindaqi
* @since 2021-02-10 20:09:34
*/
public enum EnumSingleton {
INSTANCE;
public void singletonEnumMethod() {}
}
3 小结
- 单例即单个实例化对象
- 线程安全的情况下,JVM内只有一个实例
- 实例化由类自身完成