【问题标题】:Caching techniques for objects对象的缓存技术
【发布时间】:2022-11-09 20:03:18
【问题描述】:

假设我有课程A,B,CC 有一个方法longRunningMethod,运行时间长,返回一个intAB 类都有 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?当然,简单的做法是将AB的构造函数参数更改为int,并在MyProgram中调用一次longRunningMethod。但是,传递给AB 的内容并不那么明显(允许ints?)。

【问题讨论】:

    标签: java oop caching dependency-injection


    【解决方案1】:
    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;
        }
    }
    

    【讨论】: