1. [代码]用闭包来实现接口(1) 跳至 [1] [2] [3] [全屏预览]
1 | //如果接口只有一个方法,可以通过闭包,用下面的方式来实现: |
2 |
3 | // a readable puts chars into a CharBuffer and returns the count of chars added |
4 | def readable = { it.put( "12 34" . reverse ()); 5 } as Readable |
5 |
6 | // the Scanner constructor can take a Readable |
7 | def s = new Scanner(readable) |
8 | assert s.nextInt() == 43 |
2. [代码]用闭包来实现接口(方法2)
01 | 你也可以用闭包来实现方法数多于一个的接口。当调用接口中的任何方法时,这个闭包都会被调用一次。 |
02 | 由于所有的方法都要复用这个闭包的参数表,因此典型的做法是用一个对象数组来作为底座容器。 |
03 | 这种做法也可以用于任何Groovy的闭包,并且会把所有的参数都放在这个数组中。例如: |
04 |
05 | interface X |
06 | { void f(); void g( int n); void h(String s, int n); } |
07 |
08 | x = {Object[] args -> println "method called with $args" } as X |
09 | x.f() |
10 | x.g( 1 ) |
11 | x.h( "hello" , 2 ) |
3. [代码]用Map 来实现接口(方法1)
01 | impl = [ |
02 | i: 10 , |
03 | hasNext: { impl.i > 0 }, |
04 | next: { impl.i-- }, |
05 | ] |
06 | iter = impl as Iterator |
07 | while ( iter.hasNext() ) |
08 | println iter.next() |
09 | //上面的例子只是一个故意设计的示例,但却展示了这个概念。 |
10 |
11 | //你可以仅仅实现那些真正被调用的方法,但如果你调用了一个Map 中未实现的方法时,将会抛出异常NullPointerException ,如: |
12 |
13 | interface X |
14 | { void f(); void g( int n); void h(String s, int n); } |
15 |
16 | x = [ f: { println "f called" } ] as X |
17 | x.f() |
18 | //x.g() // NPE here |