Design Pattern for constructing Enums through reflection
I am facing the following situations:
- Database entries are converted to Enums
- These entries are not the same as the Enum constants
For instance I have an entry:
Apple cake which should be mapped to the enum APPLE_CAKE
Hence, this involves character replacements, etc. before I can make the invocation to valueOf. Since I am mapping the database entities to Java objects I do it through reflections.
If an enum field is found and the database value is read I need to invoke the appropriate constructor. My current solution is to use a marker interface Entity where I have documented to implement a custom static method fromString(String).
What I don't like about this idea is that the implementer is not forced to implement the static method. So I was thinking, isn't there a fitting creational pattern which could be applied in such a situation?
The best pattern for specifing an interface for instance creation is the Abstract Factory Pattern
Make an extra interface called EntityFactory or similar. Implement a concrete factory for each Entity type. Use these factory instances to create the Entity instances.
public interface EntityFactory<T extends Entity> T create(String str); }