单例模式

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;
    }
}
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,如有问题, 可评论咨询.
原文地址:https://www.cnblogs.com/Dean0731/p/14476539.html