【发布时间】:2016-05-11 17:03:44
【问题描述】:
所以我正在尝试创建一个代表给定人员的虚构许可证号的类。许可证号由以下内容构成:
- 人名和姓氏的首字母
- 许可证颁发年份
- 一个随机的任意序列号
例如,Maggie Smith 的许可证于 1990 年颁发,其许可证号可能为 MS-1990-11,其中 11 是序列号。但是,Mark Sanders 可能在同一年获得了许可证,这意味着他的许可证的开头也可能是 MS-1990。
所以这就是问题发生的地方。我需要确保此人的序列号与 Maggie 的不同。所以我必须检查所有具有相同首字母和发行年份的记录,然后生成一个新的唯一序列号。到目前为止,这是我的代码:
public class LicenceNumber {
private final Name driverName;
private final Date issueDate;
private static final Map<String, LicenceNumber> LICENCENOS = new HashMap<String, LicenceNumber>();
public LicenceNumber(Name driverName, Date issueDate){
this.driverName = driverName;
this.issueDate = issueDate;
}
public static LicenceNumber getInstance(Name driverName, Date issueDate){
Calendar tempCal = Calendar.getInstance();
tempCal.setTime(issueDate);
String issueYear = String.valueOf(tempCal.get(Calendar.YEAR));
int serialNo = 1;
String k = driverName.getForename().substring(0, 1) + driverName.getSurname().substring(0, 1) + "-" + issueYear + "-" + serialNo;
if(!LICENCENOS.containsKey(k)){
LICENCENOS.put(k, new LicenceNumber(driverName,issueDate));
}
return LICENCENOS.get(k);
}
public boolean isUnique(){
return true;
}
public Name getDriverName() {
return driverName;
}
public Date getIssueDate() {
return issueDate;
}
}
以及如何实例化它的 sn-p:
public final class DrivingLicence {
private final Name driverName;
private final Date driverDOB;
private final Date issueDate;
private final LicenceNumber licenceNo;
private final boolean isFull;
public DrivingLicence(Name driverName, Date driverDOB, Date issueDate, boolean isFull){
//TO-DO validate inputs
this.driverName = driverName;
this.driverDOB = driverDOB;
this.issueDate = issueDate;
this.licenceNo = LicenceNumber.getInstance(driverName, issueDate);
//this.licenceNo = new LicenceNumber(driverName, issueDate);//instantiate a licence number using the driverName and dateOfIssue
this.isFull = isFull;
}
}
我基于一些讨论如何使用工厂来实现独特性的讲义。我也不确定是否应该使用 getInstance 或通过创建新对象来创建 LicenceNumber。有谁知道我可以检查给定字符串的序列号的方法,例如XX-XXXX 已经存在?
【问题讨论】:
-
这完全由数据库支持吗?我的意思是,什么构成“存在”——在什么时间范围内?
-
不,不涉及数据库。如果我正确实现了它,LicenceNumbers 会存储在 Map 中,所以我必须在那里检查。
-
我建议使用 AtomicInteger。稍后我将提供快速答复。
-
您需要小心线程问题。此外,如果您不担心 MS-1980 序列号中的“间隙”,您可以拥有一个主序列生成器。否则,您将需要为每组首字母和年份的序列生成器。
-
为什么它们必须是随机的?为什么不只是一个连续的系列?