patternjavaModerate
Creating unique registration numbers using object factories
Viewed 0 times
factoriesuniqueregistrationcreatingnumbersusingobject
Problem
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.
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 REG = new HashMap();
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;
}
}Solution
The
number, letter, and strRep fields should be final and must not be static. By making them static, you've made all of your RegistrationNumber objects very weird, and quite the opposite of immutable. Constructing one RegistrationNumber changes every previously generated RegistrationNumber!getInstance() is a bit odd. Conventionally, the name getInstance() would retrieve a singleton instance — it should the same object every time it is called. What you have instead is a method that usually generates a new object, but occasionally returns an existing object. I'm puzzled by the motivation behind that behaviour.Context
StackExchange Code Review Q#83326, answer score: 11
Revisions (0)
No revisions yet.