Java – determines which enumeration returns based on object properties
I wonder if there are any design patterns to help me solve this problem
Suppose I have a person class, which has three properties: name, nickname and speaksenglish, and an enum person type with typeone, typetwo and typethree
If a person has a nickname and speaks English, it is a typeone If it has a nickname but can't speak English, it's type two If it has no nickname, it is typethree
My first idea would be to have a method with some if else and return the associated enumeration In the future, I can have more attributes in person and other types of person types
So, my first idea is to create a method. Or switch case with a bunch of if (...) {return < persontype >, but I want to know if there are some design patterns I can use instead of IFS and switch case
Solution
I suggest you use simple inheritance and immutable objects
Therefore, first you must create an abstract class:
public abstract class AbstractPerson { private final String name; private final Optional<String> nickname; private final boolean speaksEnglish; private final PersonType personType; protected AbstractPerson(final String name,final Optional<String> nickname,final boolean speaksEnglish,final PersonType personType) { this.name = name; this.nickname = nickname; this.speaksEnglish = speaksEnglish; this.personType = personType; } public String getName() { return name; } public Optional<String> getNickname() { return nickname; } public boolean getSpeaksEnglish() { return speaksEnglish; } public PersonType getPersonType() { return personType; } }
Use the persontype enumeration:
public enum PersonType { TypeOne,TypeTwo,TypeThree; }
Now, we have three options and corresponding constructors in the subclass:
public final class EnglishSpeakingPerson extends AbstractPerson { public EnglishSpeakingPerson(final String name,final String nickname) { super(name,Optional.of(nickname),true,PersonType.TypeOne); } } public final class Person extends AbstractPerson { public Person(final String name,false,PersonType.TypeTwo); } public Person(final String name) { super(name,Optional.empty(),PersonType.TypeThree); } }
In this case, our concrete class is immutable, and its type is defined at creation time You don't need to create an if else ladder – if you want to create a new type, just create a new class / constructor