@Singleton
不管singleton是模式还是反模式,在某些情况下我们还是会使用到它的。过去我们需要创建一个私有的构造方法,然后为static属性或是初始化过的public static final属性创建一个getInstance()方法,在Java中是这样表示的:
1 public class T {
2
3 public static final T instance = new T();
4
5 private T() {}
6
7 }
2
3 public static final T instance = new T();
4
5 private T() {}
6
7 }
在Groovy 1.6中只需使用@Singleton注解你的类就行了:
@Singleton class T {}
接下来只需使用T.instance就可以访问该单例了(直接的public字段访问)。
你还可以通过额外的注解参数实现延迟加载:
@Singleton(lazy = true) class T {}
等价于下面的Groovy类:
1 class T {
2
3 private static volatile T instance
4
5 private T() {}
6
7 static T getInstance () {
8
9 if (instance) {
10
11 instance
12
13 } else {
14
15 synchronized(T) {
16
17 if (instance) {
18
19 instance
20
21 } else {
22
23 instance = new T ()
24
25 }
26
27 }
28
29 }
30
31 }
32
33 }
2
3 private static volatile T instance
4
5 private T() {}
6
7 static T getInstance () {
8
9 if (instance) {
10
11 instance
12
13 } else {
14
15 synchronized(T) {
16
17 if (instance) {
18
19 instance
20
21 } else {
22
23 instance = new T ()
24
25 }
26
27 }
28
29 }
30
31 }
32
33 }
不管是不是延迟加载,只要使用T.instance(属性访问,T.getInstance()的简写)就可以访问实例了。