現(xiàn)在讓我們看一下Groovy中的Mixin的威力吧:
//
?創(chuàng)建一個(gè)Category,以重用該類(lèi)中的靜態(tài)方法的實(shí)現(xiàn)
class ?FileCategory?{
???? // ?實(shí)現(xiàn)操作符(<<)重載(?<<?對(duì)應(yīng)的方法為leftShift?)
???? static ?leftShift(self,?other)?{
???????? // ?將"Hello,?"以及other中的內(nèi)容寫(xiě)入self表示的文件中
????????self.write( " Hello,?$other " )
????????println? " done! "
????}
}
// ?利用關(guān)鍵字use,使用之前創(chuàng)建的Category
use?(FileCategory)?{
???? // ?創(chuàng)建File的一個(gè)實(shí)例,?并將"Hello,?山風(fēng)小子"寫(xiě)入該文件中,注意不帶雙引號(hào)
???? new ?File( " hello.txt " )? << ? " 山風(fēng)小子 "
}
class ?FileCategory?{
???? // ?實(shí)現(xiàn)操作符(<<)重載(?<<?對(duì)應(yīng)的方法為leftShift?)
???? static ?leftShift(self,?other)?{
???????? // ?將"Hello,?"以及other中的內(nèi)容寫(xiě)入self表示的文件中
????????self.write( " Hello,?$other " )
????????println? " done! "
????}
}
// ?利用關(guān)鍵字use,使用之前創(chuàng)建的Category
use?(FileCategory)?{
???? // ?創(chuàng)建File的一個(gè)實(shí)例,?并將"Hello,?山風(fēng)小子"寫(xiě)入該文件中,注意不帶雙引號(hào)
???? new ?File( " hello.txt " )? << ? " 山風(fēng)小子 "
}
File類(lèi) 已經(jīng)繼承了Object類(lèi) ,但它通過(guò)Groovy中Mixin,重用了FileCategory類(lèi)中l(wèi)eftShfit方法的實(shí)現(xiàn),
其相關(guān)細(xì)節(jié)說(shuō)明已經(jīng)注于代碼中,希望大家喜歡 :)
未來(lái)Groovy的Mixin實(shí)現(xiàn):http://docs.codehaus.org/display/GroovyJSR/Mixins
而從Groovy1.6beta-2-snapshot開(kāi)始, Groovy支持如下寫(xiě)法:
//
?改自官方例子
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