• 单例模式


    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;
        }
    }
    
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,如有问题, 可评论咨询.
  • 相关阅读:
    CodeForces 363B Fence
    php结合redis实现高并发下的抢购、秒杀功能 (转载)
    PHP+Mysql基于事务处理实现转账功能的方法
    Yahoo网站性能优化的34条军规
    Cookie/Session机制详解
    PHP根据传入参数合并多个JS和CSS文件的简单实现
    PHP 使用redis实现秒杀
    PHP 常用字符串函数
    mysqldump
    局域网下关闭别人的电脑
  • 原文地址:https://www.cnblogs.com/Dean0731/p/14476539.html
Copyright © 2020-2023  润新知