java - Decide which Enum return based on object properties -
i'm wondering if there design pattern me problem.
let's have class person has 3 attributes: name, nickname , speaksenglish , enum persontype typeone, typetwo , typethree.
let's if person has nickname , speaksenglish it's typeone. if has nickame doesn't speaksenglish, it's typetwo. if not have nickame, it's typethree.
my first thought have method if-else , returning related enum. in future can have more attributes in person , other types of persontype decide.
so, first thought create method bunch of if (...) { return <persontype> } or switch-case, wondering if there design pattern can use instead of ifs , switch-case.
i recomend use simple inheritance immutable objects.
so, @ first have create 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; } } with persontype enum:
public enum persontype { typeone, typetwo, typethree; } now, have 3 options corresponding constructors in child classes:
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, final string nickname) { super(name, optional.of(nickname), false, persontype.typetwo); } public person(final string name) { super(name, optional.empty(), false, persontype.typethree); } } in case, our concrete classes immutable , type defined in moment of creation. don't need create if-else ladders - if want create new type, create new class/constructor.
Comments
Post a Comment