Ruby使用Monkey Patch猴子补丁方式进行程序开发的示例
猴子补丁(MonkeyPatch)是一种特殊的编程技巧。Monkeypatch可以用来在运行时动态地修改(扩展)类或模块。我们可以通过添加MonkeyPatch来修改不满足自己需求的第三方库,也可以添加MonkeyPatch零时修改代码中的错误。
词源
Monkeypatch最早被称作Guerrillapatch,形容这种补丁像游击队员一样狡猾。后来因为发音相似,被称为Gorillapatch。因为大猩猩不够可爱,后改称为Monkeypatch。
使用场景
以我的理解,Monkeypatch有两种使用场景:
紧急的安全性补丁,即Hotfix;
修改或扩展库中的属性和方法。
例子:
alias:
classMonkey2<Monkey defmethod2 puts"Thisismethod2" end aliasoutputmethod2 end monkey=Monkey2.new monkey.method2 monkey.output
include:
moduleHelper defhelp puts"Help..." end defmethod1 puts"helpermethod1..." end end classMonkey includeHelper defmethod1 puts"monkeymethod1..." end end monkey=Monkey.new monkey.help monkey.method1#因为重名,当前类的方法优先
undef:
classMonkey defmethod1 puts"Thisismethod1" end end classMonkey2<Monkey defmethod2 puts"Thisismethod2" end end monkey=Monkey2.new monkey.method1 monkey.method2 classMonkey2 undefmethod1 undefmethod2 end monkey.method1 monkey.method2
我们还可以使用undef_method或者remove_method实现undef<method_name>同样的功能,例子如下:
classMonkey2 remove_method:method1 undef_method:method2 nd
在使用猴子补丁的时候,还应注意如下事项:
1、基本上只追加功能
2、进行功能变更时要谨慎,尽可能的小规模
3、注意相互调用
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短