How can we implement singleton and strategy patterns using enum?

Enums can be used to implement both Singleton and Strategy design patterns in a concise, thread-safe, and maintainable manner. For Singleton, an enum guarantees a single instance and provides built-in protection against serialization and reflection attacks. For Strategy, each enum constant can define its own implementation of a common method, allowing different behaviors to be selected at runtime.

Key Points: • An enum-based Singleton is thread-safe by default and prevents multiple instance creation through serialization or reflection. • Enums can implement the Strategy Pattern by allowing each constant to provide its own behavior through method overriding. • Using enums reduces boilerplate code and results in cleaner, more maintainable implementations.

Example: A ConfigurationManager can be implemented as a Singleton using a single enum constant. Similarly, a PaymentStrategy enum can define different payment processing behaviors such as CREDIT_CARD, UPI, and NET_BANKING, with each constant implementing its own logic.

Code Example:

enum DatabaseConnection {

    INSTANCE;

    public void connect() {
        System.out.println("Database Connected");
    }
}

enum PaymentStrategy {

    CREDIT_CARD {
        @Override
        public void pay() {
            System.out.println("Paid using Credit Card");
        }
    },

    UPI {
        @Override
        public void pay() {
            System.out.println("Paid using UPI");
        }
    };

    public abstract void pay();
}

public class Main {

    public static void main(String[] args) {

        DatabaseConnection.INSTANCE.connect();

        PaymentStrategy strategy =
                PaymentStrategy.UPI;

        strategy.pay();
    }
}

Interview Tip: A concise interview answer is: An enum can implement the Singleton Pattern by defining a single constant, providing a thread-safe and serialization-safe singleton instance. For the Strategy Pattern, each enum constant can override a common method to provide different behaviors, making strategy selection simple and maintainable.