程式扎記: [ Groovy Doc ] AST : Singleton transformation

標籤

2014年9月28日 星期日

[ Groovy Doc ] AST : Singleton transformation

Source From Here 
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: 
  1. public class T {  
  2.     public static final T instance = new T();  
  3.     private T() {}  
  4. }  
You just need to annotate your type with the @Singleton annotation: 
  1. @Singleton class T {}  
The singleton instance can then simply be accessed with T.instance (direct public field access). You can also have the lazy loading approach with an additional annotation parameter: 
  1. @Singleton(lazy = trueclass T {}  
Would become more or less equivalent to this Groovy class: 
  1. class T {  
  2.     private static volatile T instance  
  3.     private T() {}  
  4.     static T getInstance () {  
  5.         if (instance) {  
  6.             instance  
  7.         } else {  
  8.             synchronized(T) {  
  9.                 if (instance) {  
  10.                     instance  
  11.                 } else {  
  12.                     instance = new T ()  
  13.                 }  
  14.             }  
  15.         }  
  16.     }  
  17. }  
Lazy or not, once again, to access the instance, simply do T.instance (property access, shorcut for T.getInstance()). 

Below is the singleton usage example: 
  1. @Singleton(strict=false,lazy=true)  
  2. class T {  
  3.     static int i=0  
  4.     public T(){i++}  
  5. }  
  6.   
  7. printf("T.i=%d\n", T.i)  // lazy=false:1, lazy=true:0  
  8. printf("T.instance.i=%d\n", T.instance.i)  
  9. printf("T.instance.i=%d\n", T.instance.i)  
  10. T t = new T()  // Not access T object through T.instance  
  11. printf("T.instance.i=%d\n", T.instance.i)  
Execution Result: 
T.i=0
T.instance.i=1
T.instance.i=1
T.instance.i=2

Supplement 
Compile-time Metaprogramming - AST Transformations

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!