使用静态工厂方法,我想创建对象(例如人),但如果正在创建具有相同条件的人,则抛出错误/异常。
我有2个类Person.java / Program.java(< -Main)
我的静态方法如下:
public class Person{
private String firstName;
private String lastName;
private Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static Person fullName(String firstName, String lastName){
/*if(firstName.equals(this.firstName)){
System.out.println("Person already exists!");
}else{
return new Person(firstName,lastName);
}*/
return new Person(firstName, lastName);
}
}
现在很明显,已经注释掉的部分不会起作用,因为人并没有实现,但我对于如何继续下去感到很遗憾。
是的,我重写了equals和hashcode!
答案 0 :(得分:1)
要实现它,您应该使用Person
集合在static
类中保留所有已创建实例的跟踪。
请注意,如果您不为它们使用弱引用,则可能会导致内存保留,而这些引用仅由Person
中定义的集合引用。
然后关于现有Person
的检查,当您覆盖equals()
和hashCode()
时,您可以从参数创建新的Person
并检查它是否已经创建
public class Person{
private String firstName;
private String lastName;
private static Set<Person> persons = new HashSet<>();
private Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
// equals and hashCode overrided relying on firstName and lastName fields
// ..
// Aditionnally to ease the creation of the exception message, override toString() too
@Override
public String toString(){
return "name=" + name +", lastName=" + lastName);
}
public static Person fullName(String firstName, String lastName){
Person p = new Person(firstName, lastName);
if (persons.contains(p)){
throw IllegalArgumentException("person " + p " already created";
}
persons.add(p);
return p;
}
}