[英]add method call to each method in a class
我上課有很多方法:
public class A {
public string method1() {
return "method1";
}
public string method2() {
return "method2";
}
public string method3() {
return "method3";
}
.
.
.
public string methodN() {
return "methodN";
}
}
我想在每個方法中添加對doSomething()的調用,例如:
public string methodi() {
doSomething();
return "methodi";
}
這樣做的最佳方法是什么? 有沒有合適的設計模式?
使用AOP已經是一個很好的答案,這也是我的第一個想法。
我試圖找出一個沒有AOP的好方法,並提出了這個想法(使用Decorator模式):
interface I {
String method1();
String method2();
...
String methodN();
}
class IDoSomethingDecorator implements I {
private final I contents;
private final Runnable commonAction;
IDoSomethingDecorator(I decoratee, Runnable commonAction){
this.contents = decoratee;
this.commonAction = commonAction;
}
String methodi() {
this.commonAction().run();
return contents.methodi();
}
}
然后你可以裝飾A的構造(它實現了我):
I a = new IDoSomethingDecorator(new A(),doSomething);
它基本上沒有火箭科學,事實上會產生比你的第一個想法更多的代碼,但你能夠注入共同的行動,並將額外的行動與A類本身分開。 此外,您可以輕松將其關閉或僅在測試中使用它。
為什么不使用單一功能?
public string methodi(int i) {
doSomething();
return "method" + i.toString();
}
或者您可以編寫一個函數,該函數接受Func參數並調用此函數而不是函數。
public string Wrapper(Func<string> action)
{
doSomething();
return action();
}
並通過此功能調用您的函數;
string temp = Wrapper(method1);
你可以使用反射。
public String callMethod(int i) {
doSomething();
java.lang.reflect.Method method;
try {
method = this.getClass().getMethod("method" + i);
} catch (NoSuchMethodException e) {
// ...
}
String retVal = null;
try {
retVal = method.invoke();
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) { }
return retVal;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.