OnJava8-Examples/patterns/SingletonPattern.java
Bruce Eckel ede3954d86 March 2021 Book Update
See notes in "Foreword to the Leanpub Edition"
2021-03-04 16:15:04 -07:00

48 lines
1.2 KiB
Java

// patterns/SingletonPattern.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
final class IntegerSingleton
implements Resource<Integer> {
private static IntegerSingleton value =
new IntegerSingleton();
private Integer i = Integer.valueOf(0);
private IntegerSingleton() {
System.out.println("IntegerSingleton()");
}
public static IntegerSingleton instance() {
return value;
}
@Override public synchronized
Integer get() { return i; }
@Override public synchronized
void set(Integer x) { i = x; }
}
public class SingletonPattern {
public static <T> void show(Resource<T> r) {
T val = r.get();
System.out.println(val);
}
public static <T> void put(Resource<T> r, T val) {
r.set(val);
}
public static void main(String[] args) {
System.out.println("Inside main()");
Resource<Integer> ir =
IntegerSingleton.instance();
Resource<Integer> ir2 =
IntegerSingleton.instance();
show(ir);
put(ir2, Integer.valueOf(9));
show(ir);
}
}
/* Output:
Inside main()
IntegerSingleton()
0
9
*/