Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added advice from Bloch 08 to a CS

...

Code Block
bgColor#ccccff
class MySingleton {
  private static MySingleton _instance;

  private MySingleton() {
    // construct object 
    // private constructor prevents instantiation by outside callers
  }

  // lazy initialization
  public static synchronized MySingleton getInstance() {
    if (_instance == null) {
      _instance = new MySingleton();
    }
    return _instance;
  }

  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }

  // Remainder of class definition 
}

See MSC38MSC37-J. Make sensitive classes noncloneable for more details about restricting the clone() method.

...