Just as enum
is recommended by Effective Java 2nd Edition to implement singleton, this solution also uses enum
to implement... quadrupleton?
import java.util.*;
public enum RoundRobin {
EENIE, MEENIE, MINY, MO;
private final static List<RoundRobin> values =
Collections.unmodifiableList(Arrays.asList(values()));
// cache it instead of creating new array every time with values()
private final static int N = values.size();
private static int counter = -1;
public static RoundRobin nextInstance() {
counter = (counter + 1) % N; // % is the remainder operator
return values.get(counter);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(RoundRobin.nextInstance());
}
// EENIE, MEENIE, MINY, MO, EENIE, MEENIE, MINY, MO, ...
}
}
Extending this to quintupleton is self-explanatory.
See also
- Effective Java 2nd Edition, Enforce singleton property with a private constructor or an enum type
As of release 1.5., there is a third approach to implementing singletons. Simply make an enum type with one element. This approach is functionally equivalent to the public field approach, except that it is more concise, provides serialization mechanism for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Related questions