Java设计模式(单例模式)——单例模式存在的问题(完整详解,附有代码+案例)

news/2024/9/22 17:33:26 标签: java, 单例模式, 设计模式, 开发语言

文章目录

4.3 单例模式存在的问题

破坏单例模式

使上面定义的单例类(Singleton)可以创建多个对象,枚举方式除外。有两种方式,分别是序列化反序列化和反射来破坏单列模式。

4.3.1序列化反序列化破环单例模式

序列化反序列化破环单例模式

java">// 懒汉式-方式4(静态内部类方式)
//序列化反序列化破环单例模式
public class Singleton implements Serializable {

    // 私有构造方法不让外界创建本类的对象
   private Singleton(){};

    // 定义静态内部类 实现单例模式
    private static class SingletonHolder{
        // 在内部类中声明并初始化外部类的对象
        // 在内部类中声明并初始化外部类的对象
        //static:保证只创建一次,final:防止外界对其修改
        private static Singleton INSTANCE = new Singleton();

    }

    // 提供对外公共的访问方式
    public static Singleton getInstance(){
        return SingletonHolder.INSTANCE;
    }

}
===========================================================
  public class Test {
    public static void main(String[] args) throws Exception{
//序列化反序列化破环单例模式

        //往文件中写对象
        // writeObjFile();

        //从文件中读取对象
        Singleton instance1 = readObjFile();
        Singleton instance2 = readObjFile();

        // singleton.demo8.Singleton@3b9a45b3
        System.out.println(instance1);
      
        // singleton.demo8.Singleton@7699a589
        System.out.println(instance2);

        boolean b = instance1 == instance2;
        System.out.println(b);//false
        //false说明创建的是两个Singleton类的对象,违背了单一规则
    }
    
    // 定义方法,将对象写出到文件中----序列化
    public static void writeObjFile() throws IOException {
        //获取Singleton类的对象
        Singleton instance = Singleton.getInstance();

        //创建对象输出流
        ObjectOutputStream oos = new ObjectOutputStream(
          new FileOutputStream("pattern\\file\\1.txt"));
      
        //将instance对象写出到文件中
        oos.writeObject(instance);

    }

    // 定义方法,将文件中的序列化对象进行反序列化读入
    public static Singleton readObjFile() throws Exception{
        //创建输入流对象
        ObjectInputStream ois = new ObjectInputStream(
              new FileInputStream("pattern\\file\\1.txt"));
      
      	//第一个读取Singleton对象
        Singleton instance = (Singleton) ois.readObject();
        return instance;
    }

    // main end.....
}

4.3.2 反射破环单例模式

java">// 懒汉式-方式4(静态内部类方式)
//反射破环单例模式
public class Singleton {
    // 私有构造方法不让外界创建本类的对象
    private Singleton (){}

    // 定义静态内部类
    private static class SingletonHolder{
        // 在内部类中声明并初始化外部类的对象
        // 在内部类中声明并初始化外部类的对象
        //static:保证只创建一次,final:防止外界对其修改
  private static final Singleton INSTANCE = new Singleton();
    }

    // 提供对外公共的访问方式
    public static Singleton getInstance(){
        return SingletonHolder.INSTANCE;
    }
}
============================================================
public class Test {
 public static void main(String[] args) throws Exception {

        //1. 获取Singleton类的字节码文件
        Class<Singleton> aClass = Singleton.class;

        //2. 获取空参构造方法
        Constructor cons = aClass.getDeclaredConstructor();

        // 3.因为空参构造是私有的,所以要取消访问检查才能创建对象
        cons.setAccessible(true);

        // 4.创建Singleton对象
        Singleton instance1 = cons.newInstance();
        Singleton instance2 = cons.newInstance();
        boolean b = instance1 == instance2;
        System.out.println(b);//false
        //false说明创建的是两个Singleton类的对象,违背了单一规则

    }
}

http://www.niftyadmin.cn/n/5670663.html

相关文章

【LandSat卫星】LandSat系列卫星介绍,文末附下载方式。

【LandSat卫星】LandSat系列卫星介绍&#xff0c;文末附下载方式。 【LandSat卫星】LandSat系列卫星介绍&#xff0c;文末附下载方式。 文章目录 【LandSat卫星】LandSat系列卫星介绍&#xff0c;文末附下载方式。前言LandSat系列卫星1.Landsat 12.Landsat 23.Landsat 34.Land…

Go并发编程的高级技巧——请求复制与限流

解锁Python编程的无限可能:《奇妙的Python》带你漫游代码世界 在一些高性能应用场景中,快速响应是非常重要的目标。例如,当一个应用需要快速响应用户的HTTP请求,或从多个副本中检索数据时,如何优化请求处理成为关键。本文将讨论如何在Go语言中,通过并发和限流机制来实现…

Stream练习

取偶数 package stream;import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors;public class StreamDemo2 {public static void main(String[] args) {ArrayList<Integer> list new ArrayList<>…

python:给1个整数,你怎么判断是否等于2的幂次方?

最近在csdn上刷到一个比较简单的题目&#xff0c;题目要求不使用循环和递归来实现检查1个整数是否等于2的幂次方&#xff0c;题目如下&#xff1a; 题目的答案如下&#xff1a; def isPowerofTwo(n):z bin(n)[2:]print(bin(n))if z[0] ! 1:return Falsefor i in z[1:]:if i !…

大学生必看!60万人在用的GPT4o大学数学智能体有多牛

❤️作者主页&#xff1a;小虚竹 ❤️作者简介&#xff1a;大家好,我是小虚竹。2022年度博客之星&#x1f3c6;&#xff0c;Java领域优质创作者&#x1f3c6;&#xff0c;CSDN博客专家&#x1f3c6;&#xff0c;华为云享专家&#x1f3c6;&#xff0c;掘金年度人气作者&#x1…

配置管理工具——omegaconf

omegaconf是专门用来解析.yaml文件&#xff0c;支持对yaml中设置参数的变量插值、类型检查、默认值处理、层次化配置。参考&#xff1a;omegaconf&#xff0c;一个超强的 Python 库&#xff01;_omeaconf-CSDN博客 主要介绍一下几个常用到的功能&#xff08;持续补充...&#…

Leetcode面试经典150题-39.组合总数

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target &#xff0c;找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 &#xff0c;并以列表形式返回。你可以按 任意顺序 返回这些组合。 candidates 中的 同一个 数字可以 无限制重复被选取 。如…

行人持刀检测数据集 voc yolo

行人持刀检测数据集 9000张 持刀检测 带标注 voc yolo 行人持刀检测数据集 数据集描述 该数据集旨在用于行人持刀行为的检测任务&#xff0c;涵盖了多种场景下的行人图像&#xff0c;特别是那些携带刀具的行人。数据集包含大量的图像及其对应的标注信息&#xff0c;可用于训练…