Example #1
0
  public static void breakSingletonWithSerialization() {
    System.out.println();

    final String fileName = "singleton.ser";
    // getting singleton instance
    Singleton instanceOne = Singleton.getInstance();
    instanceOne.setValue(10);

    try {
      // Serialize to a file
      ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream(fileName));
      objectOutput.writeObject(instanceOne);
      objectOutput.close();

      // now changed the value of singleton
      instanceOne.setValue(20);

      // Serialize to a file
      ObjectInput objectInput = new ObjectInputStream(new FileInputStream(fileName));
      Singleton instanceTwo = (Singleton) objectInput.readObject();
      objectInput.close();

      System.out.println("Instance One Value= " + instanceOne.getValue());
      System.out.println("Instance Two Value= " + instanceTwo.getValue());

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args) {
   Singleton s = Singleton.getReference();
   System.out.println(s.getValue());
   Singleton s2 = Singleton.getReference();
   s2.setValue(9);
   System.out.println(s.getValue());
   try {
     // Can't do this: compile-time error.
     // Singleton s3 = (Singleton)s2.clone();
   } catch (Exception e) {
     e.printStackTrace(System.err);
   }
 }
Example #3
0
 public static void breakSingletonWithClone() {
   System.out.println();
   final String fileName = "singleton.ser";
   // getting singleton instance
   Singleton singleton = Singleton.getInstance();
   singleton.setValue(10);
   try {
     Singleton clonedObject = (Singleton) singleton.clone();
     System.out.println(clonedObject);
     System.out.println(clonedObject.hashCode());
   } catch (CloneNotSupportedException e) {
     e.printStackTrace();
   }
 }