First they ignore you
then they ridicule you
then they fight you
then you win
    -- Mahatma Gandhi
Chinese => English     英文 => 中文             
随笔-221  评论-1047  文章-0  trackbacks-0
由于Java一种单继承的语言,即子类只能继承一个父类,所以无法重用两个类的实现,Groovy在这方面做了些改进,引入了Mixin

现在让我们看一下Groovy中的Mixin的威力吧:


//  创建一个Category,以重用该类中的静态方法的实现
class  FileCategory {
    
//  实现操作符(<<)重载( << 对应的方法为leftShift )
     static  leftShift(self, other) {
        
//  将"Hello, "以及other中的内容写入self表示的文件中
        self.write( " Hello, $other " )
        println 
" done! "
    }
}

//  利用关键字use,使用之前创建的Category
use (FileCategory) {
    
//  创建File的一个实例, 并将"Hello, 山风小子"写入该文件中,注意不带双引号
     new  File( " hello.txt " <<   " 山风小子 "
}

File类 已经继承了Object类 ,但它通过Groovy中Mixin,重用了FileCategory类中leftShfit方法的实现,
其相关细节说明已经注于代码中,希望大家喜欢 :)

未来Groovy的Mixin实现:http://docs.codehaus.org/display/GroovyJSR/Mixins


而从Groovy1.6beta-2-snapshot开始, Groovy支持如下写法:

//  改自官方例子
import  java.util.concurrent.locks. *

Object.metaClass.mixin ReentrantLock

def name 
=   " abcdef "
name.lock()
try  {
    println name.isLocked()
finally  {
    name.unlock()
}




附:朝花夕拾——Groovy & Grails

posted on 2007-11-27 22:16 山风小子 阅读(3358) 评论(5)  编辑  收藏 所属分类: Groovy & Grails