nimo23
nimo23

Reputation: 5698

enum with factory pattern

I have two solutions to create a new instance by enum type.

Both works, however, which one should I choose and why?

version 1:

public enum ColorName {
    Red(ColorRed.class),
    Green(ColorGreen.class),
    Blue(ColorBlue.class),


    ColorName(Class<?> clazz) {
        this.clazz = clazz;
    }

    private final Class<?> clazz;

    public Class<?> getClazz() {
        return clazz;
    }

    public Color createColor(String name) {

        Color c = null;

        try {
            c = (Color) this.clazz.getConstructor(String.class).newInstance(name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return c;
    }
}

version 2:

public enum ColorName {
    Red{
        @Override
        public Color newInstance(String name) {
            return new ColorRed(name);
        }
    },
    Green{
        @Override
        public Color newInstance(String name) {
            return new ColorGreen(name);
        }
    },
    Blue{
        @Override
        public Color newInstance(String name) {
            return new ColorBlue(name);
        }
    };

    public abstract Color createColor(String name);
}

In my opinion, version 2 is better (and likely faster, type safe, no reflections, no need to have try..catch).

The only benefit in version 1: smaller code (only one factory method instead of one constructor for each enum).

Are there any other benefits using version 1 instead of version 2?

Are there any better alternatives? Maybe by using Supplier?

Upvotes: 0

Views: 505

Answers (1)

Ivan Lymar
Ivan Lymar

Reputation: 2293

Java 8 functional approach:

public enum Color {

    RED(text -> new RedColor(text));
    BLUE(text -> new BlueColor(text));

    Function<String, Color> function;

    Color(Function function) {
        this.function = function;
    }

    Color getColor(String text) {
        return function.apply(text);
    }
}

I feel like this one is the "shortest" way to achieve your goal.

Upvotes: 1

Related Questions