Whether the singleton is pattern or an anti-pattern, there are still some cases where we need to create singletons. We're used to create a private constructor, a getInstance() method for a static field or even an initialized public static final field. So instead of writing code like this in Java:
- public class T {
- public static final T instance = new T();
- private T() {}
- }
- @Singleton class T {}
- @Singleton(lazy = true) class T {}
- class T {
- private static volatile T instance
- private T() {}
- static T getInstance () {
- if (instance) {
- instance
- } else {
- synchronized(T) {
- if (instance) {
- instance
- } else {
- instance = new T ()
- }
- }
- }
- }
- }
Below is the singleton usage example:
- @Singleton(strict=false,lazy=true)
- class T {
- static int i=0
- public T(){i++}
- }
- printf("T.i=%d\n", T.i) // lazy=false:1, lazy=true:0
- printf("T.instance.i=%d\n", T.instance.i)
- printf("T.instance.i=%d\n", T.instance.i)
- T t = new T() // Not access T object through T.instance
- printf("T.instance.i=%d\n", T.instance.i)
Supplement
* Compile-time Metaprogramming - AST Transformations
沒有留言:
張貼留言