Dirt-simple Java implementation of the classic singleton.
tl;dr: Singleton.eager(instance)
or Singleton.lazy(() -> instance)
No more null checking or sentinel values.
class FrozenInteger {
private final Singleton<Integer> instance;
FrozenInteger(int i) {
this.instance = Singleton.eager(i);
}
public int value() {
return this.instance.get();
}
}
(Of course... this is a too-trivial example. For primitives and immutable objects,
just use a public static final
constant.)
Singleton
is intentionally not inheritable or subclassable in Java. "Self"
Singletons are recommended to prefer composition over inheritance.
class BigImportantThing {
// All the internal state you want...
private static final Singleton<BigImportantThing> self = Singleton.lazy(() -> {
// Calls constructor, return an instance.
});
// Private constructor to prevent too many "big important things."
private BigImportantThing(/* some parameters */) {
// Some construction
}
// Static provider to get the one and only "big important thing."
public static BigImportantThing get() {
return self.get();
}
// All the methods you want...
}
There are many ways to implement singletons. (Effective Java has a couple strategies, your DI framework has one, other JVM languages have options, Google around for many more.)
This lib is good for a general-purpose Singleton implementation that can be used in many contexts.
If you have a primitive or immutable class and need a singleton, use a
public static final
value. I give you permission.
If you need more performance or less overhead, look into rolling your own implementation that works for your needs. (But wow, what would you even be doing where you'd need to create so many Singleton instances so fast?)
Singleton.eager(A)
Allows A to be null. (But don't do this)Singleton.lazy(Supplier<A>)
Allows the supplied A to be null. (But don't do this) Does throws aNullPointerException
if the supplier itself is null.- Versions of the Singleton project will only ever be single major version numbers.
Available under an MIT license.
A side quest of J.R. Hill | https://so.dang.cool | https://github.com/booniepepper