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?

Answers


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);
}

Need Your Help

Build Python scripts and call methods from C#

c# python ironpython

Is there any way to make this scenario work?

How to execute a sql stored procedure from Java Hibernate using Session Factory?

java sql spring hibernate stored-procedures

I am unable to call my stored procedure from java hibernate using session factory

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.