Created
March 21, 2023 00:00
-
-
Save thomasdarimont/c12a35cf3108759ccb4cffd72ab5f8c9 to your computer and use it in GitHub Desktop.
Instance Once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package demo; | |
public class InstanceOnceDemo { | |
public static void main(String[] args) { | |
var c1 = new MyClass(2); | |
System.out.println(c1.calc()); | |
System.out.println(c1.calc()); | |
var c2 = new MyClass(3); | |
System.out.println(c2.calc()); | |
System.out.println(c2.calc()); | |
} | |
static class MyClass { | |
private final int seed; | |
private final ClassValue<Integer> cache; | |
public MyClass(int seed) { | |
this.seed = seed; | |
this.cache = new ClassValue<>() { | |
@Override | |
protected Integer computeValue(Class<?> type) { | |
return compute(); | |
} | |
}; | |
} | |
public int calc() { | |
return this.cache.get(MyClass.class); | |
} | |
private int compute() { | |
System.out.println("Compute"); | |
return 42 * seed; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment