线程安全写法:
public class Singleton {
/* 线程安全推荐写法 */
private Singleton() {
}
static class SigletonHandler {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SigletonHandler.instance;
}
/* 线程安全双check写法 */
private static Singleton instance;
public static Singleton getInstance2() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
/* 线程安全 饿汉写法 */
private static Singleton instance2 = new Singleton();
public static Singleton getInstance3() {
return instance2;
}
}
平时用到的单例代理类:
public abstract class Lazy<T> implements AutoCloseable {
private volatile T instance = null;
protected abstract T makeObject();
protected abstract void destroyObject(T obj);
public T get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = makeObject();
}
}
}
return instance;
}
@Override
public void close() {
synchronized (this) {
if (instance != null) {
T instance_ = instance;
instance = null;
destroyObject(instance_);
}
}
}
}
调用代理类:
public class Consumer {
public static void main(String[] args) {
Lazy<MyClass> lazy = new Lazy<MyClass>() {
@Override
protected MyClass makeObject() {
return new MyClass(5);
}
@Override
protected void destroyObject(MyClass obj) {
obj.index = 0;
}
};
MyClass myClass = lazy.makeObject();
}
}
时间: 2024-09-15 14:10:06