是否存在一种设计模式(可能但不一定是OOP),您可以在每次调用其他方法时隐式(而不显式)调用一个函数/方法?
例如:
//pseudocode
class Foo {
int count = 0;
void synchronized countUp(){
count++;
}
void doSomethingFirst(){
//call countUp() implicitly here
}
void doSomethingSecond(){
//call countUp() implicitly here
}
}
例如,是否有一种在Java中使用注释的方法?我可以标记需要调用超级方法之类的方法。因此,这就像是对super的隐式调用。我并不是说这是一个好主意,我只是想知道是否可以通过某种设计模式来完成。
您可能可以复制Spring MVC框架使用的系统(我认为这不是一种设计模式)。它依赖于使继承的方法成为最终方法,并为后代提供可重载的方法。
使用部分示例代码(在Java中):
final void doSomethingFirst(){
countUp();
doSomethingFirstInternal();
}
protected void doSomethingFirstInternal() {
// Empty implementation that descendants can override when necessary.
}
我并不是说这是个好主意-您需要100%确保应首先执行代码。但这是一种选择,粗心的程序员无法引入错误,因为他们忘记了调用super()。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句