Create a single instance enumeration
enum Singleton { INSTANCE; private Field field = VALUE; public Value method(Arg arg) { } }
EDIT: The Java Enum Tutorial shows how to add fields and methods to an enumeration.
BTW: Often, when you can use Singleton, you really don't need one, since the utility class will do the same. An even shorter version is just
enum Utility {; private static Field field = VALUE; public static Value method(Arg arg) { } }
Where singletones are useful when they implement an interface. This is especially useful for testing when using dependency injection. (One of the weaknesses of using a Singleton replacement or utility in unit tests)
eg.
interface TimeService { public long currentTimeMS(); }
As you can see, if your code uses TimeService everywhere, you can enter either VanillaTimeService.INSTANCE
or new FixedTimeService()
, where you can control the time from the outside, i.e. your timestamps will be the same every time you run the test.
In short, if you don't need your singleton to implement the interface, all you might need is a utility class.
Peter Lawrey
source share