Skip to content

Instantly share code, notes, and snippets.

@MykolaBova
Created September 16, 2014 15:12
Show Gist options
  • Save MykolaBova/349c0e6314856cb11cef to your computer and use it in GitHub Desktop.
Save MykolaBova/349c0e6314856cb11cef to your computer and use it in GitHub Desktop.
LazySingleton
import junit.framework.*;
final class LazySingleton {
private int i;
private static class LazySingletonLoader {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private LazySingleton() {
if (LazySingletonLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static LazySingleton getReference() {
return LazySingletonLoader.INSTANCE;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}
public class LazySingletonPattern extends TestCase {
public void test() {
LazySingleton s = LazySingleton.getReference();
String result = "" + s.getValue();
System.out.println(result);
assertEquals(result, "0");
LazySingleton s2 = LazySingleton.getReference();
s2.setValue(9);
result = "" + s.getValue();
System.out.println(result);
assertEquals(result, "9");
try {
// Can't do this: compile-time error.
// LazySingleton s3 = (LazySingleton)s2.clone();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LazySingletonPattern.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment