I have been wondering from the designs standpoint, whether it is better to pass an enum as parameter to the factory class as opposed to a String?
Let's take the code below as an example:
class SomeFactory{
public SomeObject getObject(String objectType){
switch(objectType){
case "TYPEA":
return new SomeObjectA();
case "TYPEB":
return new SomeObjectB();
default:
{handle the situation of missing / or misspelled request here}
}
}
}
Now, I believe that the implementation above is error prone to typos and inside an IDE you would have to navigate to the factory class source and see what is acceptable as an input...
Instead of doing this I was thinking that creating a public inner enum, say called SOMEOBJECTS, and storing all possible variants there, would be a much safer choice.
The implementation would look something like this:
class SomeFactory{
// public inner enum that can be accessed through the factory.
public enum SOMEOBJECTS{
TYPEA,
TYPEB,
TYPE...
}
public SomeObject getObject(SOMEOBJECTS objectType){
switch(objectType){
case TYPEA:
return new SomeObjectA();
case TYPEB:
return new SomeObjectB();
default:
// Putting a default as a good practice, even though the input now has been
// restricted to whatever is inside the enum class.
}
}
}
The only caveat I can think of to this, is that in order to access the enum you have to type SomeFactory.SOMEOBJECTS.TYPE..;
.
Perhaps I'm obsessing over this, but I believe that this extra line of code needed in a enum class whenever updating the factory class can go a long way.
I frequently see in books and online articles the first examples of the factory pattern in Java using a String as parameter.
Would you agree with this approach or are there better ways that I am not aware of when it comes to implementing the factory pattern?
Aucun commentaire:
Enregistrer un commentaire