保证程序中只有一个对象实例的存在
常见的四种单例实现方式:
public class InstancePattern {
/**
* Author imac
* Time 2021/2/26 3:56 PM
* Description 恶汉式单例,类加载的时候实现,线程不安全
*/
public static class HungerInstance {
private static HungerInstance instance = new HungerInstance();
public static HungerInstance getInstance() {
return instance;
}
}
/**
* Author imac
* Time 2021/2/26 3:58 PM
* Description 懒汉式单例,双重判断,线程安全
*/
public static class LazyInstance {
private static LazyInstance instance = null;
public static LazyInstance getInstance() {
if (instance == null) {
synchronized (LazyInstance.class) {
if (instance == null) {
instance = new LazyInstance();
}
}
}
return instance;
}
}
/**
* Author imac
* Time 2021/2/26 4:02 PM
* Description 枚举单例,线程安全
*/
public static enum EnumInstance {
INSTANCE,
}
/**
* Author imac
* Time 2021/2/26 4:03 PM
* Description 内部类持有的单例,线程安全
*/
public static class InnerClassInstance {
private static class InnerHolder {
protected static InnerClassInstance instance = new InnerClassInstance();
}
public static InnerClassInstance getInstance() {
return InnerHolder.instance;
}
}
}
网友评论