Hierarchical/Grouping enum :
We have different statuses and under each status there were
sub statuses. We don’t want to check in switch or/if-else each sub statuses so
we will check the main status.
public enum Status
{
ACTIVE1(Group.ACTIVE, "active
value 1"),
ACTIVE2(Group.ACTIVE, "active
value 2"),
ACTIVE3(Group.ACTIVE, "active
value 3"),
BLOCKED1(Group. BLOCKED, "blocked
value 1"),
BLOCKED2(Group. BLOCKED, "blocked
value 2"),
BLOCKED3(Group. BLOCKED, "blocked
value 3");
public enum Group
{
ACTIVE, BLOCKED;
}
private String value;
private Group group;
private Status(Group group, final String value)
{
this.value = value;
this.group = group;
}
public String getValue()
{
return this.value;
}
public Group getGroup()
{
return this.group;
}
public boolean isInGroup(Group group)
{
return this.group == group;
}
}
Using this enum in our conditional statements :
switch(statusObject.getGroup())
{
case ACTIVE:
case BLOCKED:
}
If(ACTIVE1.isInGroup(Group.ACTIVE)) // true
References: