[agent] refactor patchDefine

+ wrap the patchDefine in a closure
+ extract patchFactoryFunction function
+ add lots of comments