Reputation: 1
I'm learning factories concept in Java, and I have one question because most of the Java tutorial suggest implementing factory like this:
public class factory1 {
public static Dao getDao(Object entity) {
if (entity instanceof E_Competence) {
return new JpaDaoCompetence();
}
if (entity instanceof E_Categorie) {
return new JpaDaoCategorie();
} else {
throw new IllegalArgumentException("Unknown entity type.");
}
}
}
But I would have tended to do it like that:
public class factory2 {
public static Dao getDao(E_Competence entity) {
return new JpaDaoCompetence();
}
public static Dao getDao(E_Categorie entity) {
return new JpaDaoCategorie();
}
}
I would like to know which is the best way to do and why.
Upvotes: 0
Views: 179
Reputation: 8163
It depends
Sometimes you want to have one factory per type you are producing. Sometimes you have a whole inheritance hierarchy of factories. Sometimes you have a factory like you are showing, that can produce different objects.
Sometimes your second example works. And sometimes it doesn't, and you need the first one.
The issue comes when whatever calls the factory methods doesn't know itself what type entity
is. In that case the compiler can't know which of the two methods is being called. Could happen if there is a lot of indirection, for example.
Upvotes: 1