Reputation: 179
Using static factory method, I want to create objects (e.g. persons), but throw an error/exception if a person with the same criteria is being created.
I have 2 classes Person.java / Program.java (<-Main)
My static method is as follow:
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);
}
}
Now obviously the commented-out part wouldn't work because Person isn't instanciated, but I'm kind of lost about how I could go on.
And yes, I'm overriding equals and hashcode!
Upvotes: 0
Views: 269
Reputation: 131466
To achieve it you should keep traces of all created instances in the Person
class by using a static
collection.
Note that it may cause memory retention if you don't use weak references for them and these are only referenced by the collection defined in Person
.
Then about the check of an existing Person
, as you overrided equals()
and hashCode()
, you could create a new Person
from the parameters and check whether it was already created.
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;
}
}
Upvotes: 1