現(xiàn)在讓我們看一下Groovy中的Mixin的威力吧:
//
?創(chuàng)建一個Category,以重用該類中的靜態(tài)方法的實現(xiàn)
class ?FileCategory?{
???? // ?實現(xiàn)操作符(<<)重載(?<<?對應的方法為leftShift?)
???? static ?leftShift(self,?other)?{
???????? // ?將"Hello,?"以及other中的內容寫入self表示的文件中
????????self.write( " Hello,?$other " )
????????println? " done! "
????}
}
// ?利用關鍵字use,使用之前創(chuàng)建的Category
use?(FileCategory)?{
???? // ?創(chuàng)建File的一個實例,?并將"Hello,?山風小子"寫入該文件中,注意不帶雙引號
???? new ?File( " hello.txt " )? << ? " 山風小子 "
}
class ?FileCategory?{
???? // ?實現(xiàn)操作符(<<)重載(?<<?對應的方法為leftShift?)
???? static ?leftShift(self,?other)?{
???????? // ?將"Hello,?"以及other中的內容寫入self表示的文件中
????????self.write( " Hello,?$other " )
????????println? " done! "
????}
}
// ?利用關鍵字use,使用之前創(chuàng)建的Category
use?(FileCategory)?{
???? // ?創(chuàng)建File的一個實例,?并將"Hello,?山風小子"寫入該文件中,注意不帶雙引號
???? new ?File( " hello.txt " )? << ? " 山風小子 "
}
File類 已經(jīng)繼承了Object類 ,但它通過Groovy中Mixin,重用了FileCategory類中l(wèi)eftShfit方法的實現(xiàn),
其相關細節(jié)說明已經(jīng)注于代碼中,希望大家喜歡 :)
未來Groovy的Mixin實現(xiàn):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()
}
import ?java.util.concurrent.locks. *
Object.metaClass.mixin?ReentrantLock
def?name? = ? " abcdef "
name.lock()
try ?{
????println?name.isLocked()
}? finally ?{
????name.unlock()
}
附:朝花夕拾——Groovy & Grails