假设我有A、B、C类。C有一个方法longRunningMethod,它需要很长时间才能运行并返回int。类A和B都有C作为依赖项,并且需要调用方法longRunningMethod。
public class A{
private C c;
public A(C c){
this.c = c;
}
public void method1(){
this.c.longRunningMethod();
}
}public class B{
private C c;
public A(C c){
this.c = c;
}
public void method2(){
this.c.longRunningMethod();
}
}public class C{
public int longRunningMethod(){
...
}
}public class MyProgram{
public static void main(String[] args){
C c = new C();
A a = new A(c);
B b = new B(c);
a.method1();
b.method2()//avoid calling c.longRunningMethod();
}
}可以采取哪些方法来避免两次调用longRunningMethod?当然,简单的方法是将A和B的构造函数参数更改为int,并在MyProgram中调用longRunningMethod。但是,传递给A和B的内容并不那么明显(哪些int是允许的?)
发布于 2022-11-09 12:03:18
public class C{
private boolean wasCalled = false;
private int cachedValue;
public int longRunningMethod(){
if (!wasCalled) {
// do your long running job here and set result to cachedValue
wasCalled = true;
}
return cachedValue;
}
}https://stackoverflow.com/questions/74373311
复制相似问题