package interview;

/** Three thread-safe singleton styles interviewers ask about. */
public final class Singletons {
    private Singletons() {}

    /** Enum singleton: serialization- and reflection-safe. */
    public enum Registry {
        INSTANCE;
        private int counter;
        public synchronized int next() { return ++counter; }
    }

    /** Initialization-on-demand holder: lazy, thread-safe, no locking on reads. */
    public static final class Config {
        private Config() {}
        private static final class Holder { static final Config INSTANCE = new Config(); }
        public static Config getInstance() { return Holder.INSTANCE; }
    }

    /** Double-checked locking: needs volatile so other threads never see a half-built object. */
    public static final class Connection {
        private static volatile Connection instance;
        private Connection() {}
        public static Connection getInstance() {
            Connection local = instance;
            if (local == null) {
                synchronized (Connection.class) {
                    local = instance;
                    if (local == null) instance = local = new Connection();
                }
            }
            return local;
        }
    }
}
