随着 Java 8 的出现以及对ConcurrentMap
lambda 的一些改进,现在可以以更整洁的方式实现 a Multiton
(甚至可能是 a ):Singleton
public class Multiton {
// Map from the index to the item.
private static final ConcurrentMap<Integer, Multiton> multitons = new ConcurrentHashMap<>();
private Multiton() {
// Possibly heavy construction.
}
// Get the instance associated with the specified key.
public static Multiton getInstance(final Integer key) throws InterruptedException, ExecutionException {
// Already made?
Multiton m = multitons.get(key);
if (m == null) {
// Put it in - only create if still necessary.
m = multitons.computeIfAbsent(key, k -> new Multiton());
}
return m;
}
}
我怀疑——尽管这会让我感到不舒服——getInstance
可以进一步最小化为:
// Get the instance associated with the specified key.
public static Multiton getInstance(final Integer key) throws InterruptedException, ExecutionException {
// Put it in - only create if still necessary.
return multitons.computeIfAbsent(key, k -> new Multiton());
}