I want to create a Factory which returns dao-instance, depending on the Class clazz
Teammember, Scene and Equipment are my Model Classes.
My DAO’s look like this:
public class JDBCTeammemberDAO implements JdbcDAO<Teammember>
my Factory looks like this:
public class DAOFactory {
JdbcDAO createDAO(Class clazz) {
if(clazz.equals(Teammember.class)) {
return new JDBCTeammemberDAO();
}
if(clazz.equals(Scene.class)) {
return new JDBCSceneDAO();
}
if(clazz.equals(Equipment.class)) {
return new JDBCEquipmentDAO();
}
return null;
}
}
I was thinking about switch and polymorphism, but I couldn’t figure out how.
Basically I want to find the Implementation “SomeClass implements JdbcDAO”
My first approach was:
String name = clazz.getName().substring(6); // model.Teammember
Class<?> forName;
try {
forName = Class.forName("dao.jdbc.JDBC" + name + "DAO");
return (JdbcDAO) forName.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
but I don’t feel good with handling this with String method. Besides, it doesn’t work, if I have different Model and Dao names (like: JDBCMemberDAO instead of JDBCTeammemberDAO)
I was in a similar situation and decided to use a Dao registry to handle the issue. Using the generic dao pattern @Perception mentioned:
Then you can have your
DaoRegistry would look something like this:
This is just the jest of it, you will need to make sure it is thread-safe. Hope this helps.