Nao*_*aor 7 c# java design-patterns
我上课有很多方法:
public class A {
public string method1() {
return "method1";
}
public string method2() {
return "method2";
}
public string method3() {
return "method3";
}
.
.
.
public string methodN() {
return "methodN";
}
}
Run Code Online (Sandbox Code Playgroud)
我想在每个方法中添加对doSomething()的调用,例如:
public string methodi() {
doSomething();
return "methodi";
}
Run Code Online (Sandbox Code Playgroud)
这样做的最佳方法是什么?有没有合适的设计模式?
使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以装饰A的构造(它实现了我):
I a = new IDoSomethingDecorator(new A(),doSomething);
Run Code Online (Sandbox Code Playgroud)
它基本上没有火箭科学,事实上会产生比你的第一个想法更多的代码,但你能够注入共同的行动,并将额外的行动与A类本身分开.此外,您可以轻松将其关闭或仅在测试中使用它.
| 归档时间: |
|
| 查看次数: |
2373 次 |
| 最近记录: |