Sobes.tech
Junior — Middle

Which design pattern is used to implement enumerations?

sobes.tech AI

Answer from AI

The pattern often used for implementing enumerations (enums) is the "Typesafe Enum" pattern. In Java, before the introduction of the built-in enum (before Java 5), this pattern was implemented by creating a class with a private constructor and a set of public static final instances of that class.

Example:

public class Day {
    public static final Day MONDAY = new Day("Monday");
    public static final Day TUESDAY = new Day("Tuesday");

    private String name;

    private Day(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

With the advent of enum in Java 5, it is recommended to use the built-in enum, which implements this pattern at the language level.