单例模式

Dean0731 27天前 ⋅ 35 阅读
import java.io.Serializable;
// 修改后的单例模式
 
// 使用线程同步创建,防止进程切换重复创建线程,
// 设置volatile关键字修饰,使读取singleton对象时能够获取最新状态
// 修改构造方法,防止反射创建对象
// 修改readResolve方法,防止反序列化对象时重新创建对象
// 重写克隆方法,防止对象克隆
public class Singleton2 implements Serializable, Cloneable {
    private static volatile Singleton2 singleton;
 
    private Singleton2() {
        if (singleton != null) {
            throw new RuntimeException("对象已被创建");
        }
    }
    public static Singleton2 getInstance() {
        if (singleton == null) {
            synchronized (singleton) {
                if (singleton == null)
                    singleton = new Singleton2();
            }
        }
        return singleton;
    }
 
    private Object readResolve() {
        return singleton;
    }
 
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return getInstance();
    }
}
// 还可以创建
Constructor<Singleton2> con = Singleton2.class.getDeclaredConstructor(null);
con.setAccessible(true);
Singleton2 s1 = con.newInstance();
Singleton2 s2 = con.newInstance();
System.out.println(s1);
System.out.println(s2);
// 枚举方式,可以完全防止反射
enum Singleton2 implements Serializable,Cloneable{
    Singleton2;
    public Singleton2 getInstance(){
        return Singleton2;
    }
}

全部评论: 0

    我有话说: