gpt4 book ai didi

java - OOP 设计模式 - 隐式调用 super 方法或其他解决方案

转载 作者:行者123 更新时间:2023-12-02 04:40:05 26 4
gpt4 key购买 nike

是否存在一种设计模式(可能但不一定是 OOP),使您可以在每次调用对象中的所有其他方法时隐式(非显式)调用一个函数/方法 A?

例如:

//pseudocode

class Foo {

int count = 0;

void synchronized countUp(){
count++;
}

void doSomethingFirst(){
//call countUp() implicitly here
}

void doSomethingSecond(){
//call countUp() implicitly here
}
}

例如,有没有办法在 Java 中使用注释?我可以标记需要调用 super 方法或其他方法的方法。所以这就像对 super 的隐式调用。我并不是说这是一个好主意,我只是想知道是否可以通过设计模式以某种方式完成它。

最佳答案

您可能可以复制 Spring MVC 框架使用的系统(我不认为这是一种设计模式)。它依赖于使继承的方法成为 final方法,并为后代提供可重载的方法。

使用部分示例代码(Java 语言):

   final void doSomethingFirst(){
countUp();
doSomethingFirstInternal();
}

protected void doSomethingFirstInternal() {
// Empty implementation that descendants can override when necessary.
}

我并不是说这是一个好主意 - 您需要 100% 确定您的代码应该首先执行。 But 是一个选项,粗心的程序员不会因为忘记调用 super() 而引入错误。

关于java - OOP 设计模式 - 隐式调用 super 方法或其他解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com