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?

Mahoni
  • 7,088
  • 17
  • 58
  • 115
  • You can mandate a companion singleton object for each enum that implements your common interface. – Marko Topolnik Aug 24 '12 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. – Cephalopod Aug 24 '12 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 : http://stackoverflow.com/a/1080912/241986 – Boris Treukhov Aug 24 '12 at 21:01

1 Answers1

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);
}
bjorncs
  • 1,250
  • 11
  • 20
  • Yeah, the only disadvantage I see in that, that for 10 Enums I have then 10 Interfaces, quiete bloaty – Mahoni Aug 24 '12 at 20:47
  • Indeed, but that's the cost if you want to specify fromString(String) as an Interface "contract". – bjorncs Aug 24 '12 at 20:49
  • 1
    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. – Cephalopod Aug 24 '12 at 20:52
  • @Arian kudos, the annotation and inner class implementation is really great! – Mahoni Aug 24 '12 at 20:56
  • 1
    Agree, that is definitively a sexy solution to problem! – bjorncs Aug 24 '12 at 21:23