Monkey Patch猴子补丁是指在程序解释运行时动态添加类或模块的做法,这里我们就来看一下Ruby使用Monkey Patch猴子补丁方式进行程序开发的示例
猴子补丁(Monkey Patch)是一种特殊的编程技巧。Monkey patch 可以用来在运行时动态地修改(扩展)类或模块。我们可以通过添加 Monkey Patch 来修改不满足自己需求的第三方库,也可以添加 Monkey Patch 零时修改代码中的错误。
词源
Monkey patch 最早被称作 Guerrilla patch,形容这种补丁像游击队员一样狡猾。后来因为发音相似,被称为 Gorilla patch。因为大猩猩不够可爱,后改称为 Monkey patch。
使用场景
以我的理解,Monkey patch 有两种使用场景:
紧急的安全性补丁,即 Hotfix;
修改或扩展库中的属性和方法。
例子:
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#因为重名,当前类的方法优先
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实现undef <method_name>同样的功能,例子如下:
class Monkey2
remove_method :method1
undef_method :method2
nd
在使用猴子补丁的时候,还应注意如下事项:
1、基本上只追加功能
2、进行功能变更时要谨慎,尽可能的小规模
3、注意相互调用
本文标题为:Ruby使用Monkey Patch猴子补丁方式进行程序开发的示例
- Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
- Ruby 迭代器知识汇总 2023-07-23
- Go Web开发进阶实战(gin框架) 2023-09-06
- R语言-如何切换科学计数法和更换小数点位数 2022-11-23
- R语言绘图数据可视化pie chart饼图 2022-12-10
- Ruby的字符串与数组求最大值的相关问题讨论 2023-07-22
- Golang http.Client设置超时 2023-09-05
- 汇编语言程序设计之根据输入改变屏幕颜色的代码 2023-07-06
- Swift超详细讲解指针 2023-07-08
- R语言关于二项分布知识点总结 2022-11-30
