Good practice for instantiating classes from an enumeration value

I searched a lot of places, but I did not find a good answer for my problem:

I have an enumeration, for example:

public enum Window { CLASSIC, MODERN } 

and I need to separate the behavior of my application according to the enum value, for example:

 switch (myWindow.getType()) { case CLASSIC: new ClassicWindow(...); case MODERN: new ModernWindow(...); } 

I know what you think: just put this in enum and basta, however this is not the only class that depends on my listing! And I canโ€™t write as many methods of creating objects as I have objects!

Simply put, what can I do in this situation? A friend of mine told me to get rid of the enumeration and use the derived classes every time, but in the end I would have to create as many instances as there are subclasses for all my tests!

In short, I'm stuck.

Do you know what is best for this? Thanks

+4
source share
3 answers

You seem to be looking for a design pattern, not best practices for using enumerations. The code that you intend to write will be populated with switch statements, with one condition for each possible value of the enumeration, which makes it difficult to maintain and expand in the long run. A better idea would be to reorganize every possible case behavior in a separate class, possibly using the Factory Abstract Template .

0
source

This is a factory template. This example actually shows what you are doing.

0
source

You can either implement the interface in your enumeration, or make them act like a factory:

 interface WindowBuilder { Window makeWindow(); } enum WindowType implements WindowBuilder { SIMPLE { public Window makeWindow() { return new SimpleWindow() } }, [... other enums] } 

or you can use reflection and bind the class to the enum type so that they (again) work like a factory:

 enum WindowType { SIMPLE(SimpleWindow.class), [... other enums] private final Class<? extends Window> wndType; private WindowType(Class<? extends Window> wndType) { this.wndType = wndType; } public Window makeWindow() { // in fact you will need to either catch the exceptions newInstance can throw, or declare the method can throw them return this.wndType.newInstance(); } } 

In any case, you can call them the following:

 Window window = myWindow.getType().makeWindow(); 
0
source

All Articles