Multiton Design Pattern
Aliases π: None
Description π: This pattern is a generalization of the singleton pattern with n
instances instead of 1
.
Advantages β
- Same as a singleton
Disadvantages π«
- Same as a singleton
Notes π
- We use
getInstance(xxx)
withxxx
something to identify which instance you want (ex: an int, a string...).
Java implementation
Lazy instantiation
public class RpgMaker {
private static final int MAX_INSTANCE = 5;
private static ArrayList<RpgMaker> instance = null;
// get instance
public static RpgMaker getInstance(int i) {
if (i > MAX_INSTANCE || i < 0) throw new IllegalArgumentException("not a valid key");
if (instance == null) {
// initialization
instance = new ArrayList<>();
// fill the list
for (int j = 0; j < MAX_INSTANCE; j++) {
instance.add(new RpgMaker());
}
}
return instance.get(i);
}
// private !!!
private RpgMaker(){}
}
Early instantiation
public class RpgMaker {
private static final int MAX_INSTANCE = 5;
// initialization
private static final ArrayList<RpgMaker> instance = new ArrayList<>();
static {
// fill the list
for (int j = 0; j < MAX_INSTANCE; j++) {
instance.add(new RpgMaker());
}
}
// get instance
public static RpgMaker getInstance(int i) {
if (i > MAX_INSTANCE || i < 0) throw new IllegalArgumentException("not a valid key");
return instance.get(i);
}
// private !!!
private RpgMaker(){}
}