Singleton pattern with combination of lazy loading and thread safety
http://stackoverflow.com/questions/15792186/singleton-pattern-with-combination-of-lazy-loading-and-thread-safety
<<
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Комментариев нет:
Отправить комментарий