I'm learning about immutability and uniqueness in Java, particularly the use of defensive programming and object factories.
I have been asked to create a class containing an object factory that when called creates a unique registration number comprised of a single letter and 4 digits. I think my solution ticks all boxes, but would appreciate some input on this one before I go any further to see if I'm on the right track.
public class RegistrationNumber
{
private static final Map<String, RegistrationNumber> REG = new HashMap<String, RegistrationNumber>();
private static int number;
private static char letter;
private static String strRep;
private RegistrationNumber(int number, char letter, String strRep) {
this.number = number;
this.letter = letter;
this.strRep = strRep;
}
public static final RegistrationNumber getInstance() {
Random r = new Random();
int numbers = r.nextInt(9000) + 1000;
Character letter = (char)(r.nextInt(26) + 'a');
String strRep = letter + "" + numbers;
RegistrationNumber n = REG.get(strRep);
if (n == null) {
n = new RegistrationNumber(numbers, letter, strRep);
REG.put(strRep, n);
}
return n;
}
char getLetter() {
return letter;
}
int getNumbers() {
return number;
}
public String toString() {
return strRep;
}
}