0

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?

3
  • You can mandate a companion singleton object for each enum that implements your common interface. Commented Aug 24, 2012 at 20:35
  • 1
    I suppose when you say "entry", you mean a string, and when you say "invoke the constructor", you mean to get the enum constant, because you cannot invoke constructors of enums in your application code. Commented Aug 24, 2012 at 20:48
  • If you're calling valueOf then you know the class of the enum you are calling - why can't you add a public static MyEnum lookup(String text) to your enum? 0_0 Also I would not use the slow reflection at all in this case, usually I use a look up table for this : stackoverflow.com/a/1080912/241986 Commented Aug 24, 2012 at 21:01

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah, the only disadvantage I see in that, that for 10 Enums I have then 10 Interfaces, quiete bloaty
Indeed, but that's the cost if you want to specify fromString(String) as an Interface "contract".
You would only have one interface, but 10 implementations. But you need to implement 10 parse-methods anyway, so whats the problem. If you have the implementation as an static inner class in the enum, you don't even need an extra file. You can then annotate the enum class to point to the factory implementation.
@Arian kudos, the annotation and inner class implementation is really great!
Agree, that is definitively a sexy solution to problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.