猴子補(bǔ)丁(Monkey Patch)是一種特殊的編程技巧。Monkey patch 可以用來在運(yùn)行時(shí)動(dòng)態(tài)地修改(擴(kuò)展)類或模塊。我們可以通過添加 Monkey Patch 來修改不滿足自己需求的第三方庫,也可以添加 Monkey Patch 零時(shí)修改代碼中的錯(cuò)誤。
詞源
Monkey patch 最早被稱作 Guerrilla patch,形容這種補(bǔ)丁像游擊隊(duì)員一樣狡猾。后來因?yàn)榘l(fā)音相似,被稱為 Gorilla patch。因?yàn)榇笮尚刹粔蚩蓯郏蟾姆Q為 Monkey patch。
使用場(chǎng)景
以我的理解,Monkey patch 有兩種使用場(chǎng)景:
緊急的安全性補(bǔ)丁,即 Hotfix;
修改或擴(kuò)展庫中的屬性和方法。
例子:
alias:
class Monkey2 < Monkey def method2 puts "This is method2" end alias output method2 end monkey = Monkey2.new monkey.method2 monkey.output
include:
module Helper def help puts "Help..." end def method1 puts "helper method1..." end end class Monkey include Helper def method1 puts "monkey method1..." end end monkey = Monkey.new monkey.help monkey.method1#因?yàn)橹孛?dāng)前類的方法優(yōu)先
undef:
class Monkey def method1 puts "This is method1" end end class Monkey2 < Monkey def method2 puts "This is method2" end end monkey = Monkey2.new monkey.method1 monkey.method2 class Monkey2 undef method1 undef method2 end monkey.method1 monkey.method2
我們還可以使用undef_method或者remove_method實(shí)現(xiàn)undef <method_name>同樣的功能,例子如下:
class Monkey2 remove_method :method1 undef_method :method2 nd
在使用猴子補(bǔ)丁的時(shí)候,還應(yīng)注意如下事項(xiàng):
1、基本上只追加功能
2、進(jìn)行功能變更時(shí)要謹(jǐn)慎,盡可能的小規(guī)模
3、注意相互調(diào)用
新聞熱點(diǎn)
疑難解答
圖片精選