设计模式-单例模式(下)

前言


单例模式有多种模式,正常情况下,单例模式只生成一个实例,但是通过一定的方式,可以破坏单例模式。下面我们看一下常见的破坏单例模式的方法。

问题演示

通常破坏单例模式(除枚举方式)有两种方法,分别是序列化和反射。

序列化和反序列化

Singleton类:

public class Singleton implements Serializable { 
  //私有构造方法 
  private Singleton() {}
  private static class SingletonHolder {
    private static final Singleton INSTANCE = new Singleton();
  }
  //对外提供静态方法获取该对象
  public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
  } 
}

Test类

   ```java
   public class Test { 
       public static void main(String[] args) throws Exception { 
         //往文件中写对象 
         //writeObject2File(); 
         //从文件中读取对象
         Singleton s1 = readObjectFromFile();
         Singleton s2 = readObjectFromFile();
         //判断两个反序列化后的对象是否是同一个对象
         System.out.println(s1 == s2);
       }
       private static Singleton readObjectFromFile() throws Exception { 
         //创建对象输入流对象
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/a.txt"));
         //第一个读取Singleton对象
         Singleton instance = (Singleton) ois.readObject();
         return instance;
       }
       public static void writeObject2File() throws Exception {
         //获取Singleton类的对象
         Singleton instance = Singleton.getInstance();
         //创建对象输出流
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Think\\Desktop\\a.txt"));
         //将instance对象写出到文件中
         oos.writeObject(instance);
       }
     }
   ```

上面代码运行结果是 false ,表明序列化和反序列化已经破坏了单例设计模式。

反射

Singleton类

public class Singleton {
  //私有构造方法 
  private Singleton() {}
  private static volatile Singleton instance; 
  //对外提供静态方法获取该对象 
  public static Singleton getInstance() { 
    if(instance != null) { 
      return instance;
    }
    synchronized (Singleton.class) {
      if(instance != null) { 
        return instance;
      }
      instance = new Singleton();
      return instance;
    }
  } 
}

Test类:

public class Test {
  public static void main(String[] args) throws Exception { 
  //获取Singleton类的字节码对象
  Class clazz = Singleton.class;
  //获取Singleton类的私有无参构造方法对象
  Constructor constructor = clazz.getDeclaredConstructor();
  //取消访问检查
  constructor.setAccessible(true);
  //创建Singleton类的对象s1
  Singleton s1 = (Singleton) constructor.newInstance();
  //创建Singleton类的对象s2
  Singleton s2 = (Singleton) constructor.newInstance();
  //判断通过反射创建的两个Singleton对象是否是同一个对象
  System.out.println(s1 == s2); 
  } 
}

上面代码运行结果是 false ,表明序列化和反序列化已经破坏了单例设计模式

如何解决?

序列化、反序列方式破坏单例模式的解决方法

在Singleton类中添加 readResolve() 方法,在反序列化时被反射调用,如果定义了这个方法,

就返回这个方法的值,如果没有定义,则返回新new出来的对象。

Singleton类:

public class Singleton implements Serializable { 
  //私有构造方法 
  private Singleton() {} 
  private static class SingletonHolder { 
    private static final Singleton INSTANCE = new Singleton();
  }
  //对外提供静态方法获取该对象
  public static Singleton getInstance() { 
    return SingletonHolder.INSTANCE; 
  }
  /**
  * 下面是为了解决序列化反序列化破解单例模式 
  */ 
  private Object readResolve() {
    return SingletonHolder.INSTANCE;
  } 
}

反射方式破解单例的解决方法

public class Singleton {
  //私有构造方法
  private Singleton() {
    /* 
    反射破解单例模式需要添加的代码 
    */
    if(instance != null) { 
      throw new RuntimeException(); 
    } 
  }
  private static volatile Singleton instance; 
  //对外提供静态方法获取该对象
  public static Singleton getInstance() { 
    if(instance != null) {
      return instance; 
    }
    synchronized (Singleton.class) {
      if(instance != null) { 
        return instance; 
      }
      instance = new Singleton();
      return instance; 
    } 
  } 
}

说明:

这种方式比较好理解。当通过反射方式调用构造方法进行创建创建时,直接抛异常。不运行此中操作。

JDK中的单例应用

Runtime类就是使用的单例设计模式

  • 源码

    public class Runtime {
      private static Runtime currentRuntime = new Runtime(); 
      /**
      * Returns the runtime object associated with the current Java application.
      * Most of the methods of class <code>Runtime</code> are instance
      * methods and must be invoked with respect to the current runtime object.
      * @return the <code>Runtime</code> object associated with the current
      * Java application. 
      */ 
      public static Runtime getRuntime() { 
        return currentRuntime; 
      }
      /** Don't let anyone else instantiate this class */ 
      private Runtime() {} 
      ... 
    }
    

    从上面源代码中可以看出Runtime类使用的是恶汉式(静态属性)方式来实现单例模式的。

  • 使用Runtime类中的方法

    public class RuntimeDemo { 
      public static void main(String[] args) throws IOException { 
        //获取Runtime类对象
        Runtime runtime = Runtime.getRuntime(); 
        //返回 Java 虚拟机中的内存总量。
        System.out.println(runtime.totalMemory()); 
        //返回 Java 虚拟机试图使用的最大内存量。 
        System.out.println(runtime.maxMemory());
        //创建一个新的进程执行指定的字符串命令,返回进程对象 
        Process process = runtime.exec("ipconfig");
        //获取命令执行后的结果,通过输入流获取
        InputStream inputStream = process.getInputStream();
        byte[] arr = new byte[1024 * 1024* 100];
        int b = inputStream.read(arr);
        System.out.println(new String(arr,0,b,"gbk"));
      } 
    }
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容