Sobes.tech
Junior — Middle

Kas saaksite selgitada Pattern String Enum kontseptsiooni ja selle eeliseid?

sobes.tech AI

Vastus AI-lt

Pattern String Enum — this is an approach in Java where, instead of using a standard enum with fixed values, a class is created with a set of static string constants that mimic an enumeration. This pattern is useful when you need a set of fixed string values but also want to ensure greater flexibility, for example, the ability to extend the set of values without recompilation.

Advantages:

  • Strings can be used directly, which is convenient for integration with external systems (e.g., JSON, databases).
  • The set of values can be easily extended without changing the enum.
  • Methods and logic that are not available in standard enums can be added.

Example:

public class Status {
    public static final String NEW = "NEW";
    public static final String IN_PROGRESS = "IN_PROGRESS";
    public static final String DONE = "DONE";

    private Status() {} // prevent instantiation
}

This approach is often used when values come from external sources and are not fixed at compile time.