Use Enum or String for a static factory method?
Is it better to use enum
or String
to dispatch to the right object to create in a static
factory method ?
Example with String
:
public static Car createCar(String carName){
if(carName.equals("Ferrari")){
return new Ferrari();
}
else if(carName.equals("Porsche")){
return new Porsche();
}
....
}
Example with enum
:
public static Car createCar(CarEnum carEnum){
if(CarEnum.FERRARI.equals(carEnum)){
return new Ferrari();
}
else if(CarEnum.PORSCHE.equals(carEnum)){
return new Porsche();
}
....
}
For now, according to me :
Benefit of using enum
:
- Avoid that the user calls the factory with a non-treated
carName
.
Drawback of using Enum
:
Increase dependencies because a ch开发者_开发问答ange into enum
(FERRARI
becoming ENZO_FERRARI
for instance) will require modification on client. However, with String
we could redirect Ferrari
to Enzo Ferrari
instance without recompile client code. Of course, we could make the same thing for client using old enum
values with a redirection of FERRARI
to ENZO-FERRARI
enum
but for me it implies that enum
would have to keep old values to make client compatible... no make sense for me.
I would like to know what are your opinions on this subject?
If, as you do in this case, you have a fixed number of acceptable arguments to a method, then it's best to enforce that constraint as best as you can on the clients of the method. In this case, accepting any old string would cause more failures than using an enum.
However, you might also consider, in a limited case like this, using named factory methods for each type of car: like createFerrari(), createPorsche() etc.
Neither. Use an Enum and make the method an instance method of the Enum itself. No if's required.
I would use Enums
; I don't like Strings used in this case. The advantage with enums is that you could switch over them (which will not work with strings) and you don't need to handle false input.
I wouldn't add instance methods to enums. Today we saw strange unexpected behaviour when using static blocks in enums and refering to enums. Suddenly an enum instance was null!!!???
I would use an abstract factory pattern. This way you could use the same factory for two enum instances.
I would also use a hashmap to store the factories. This way you don't have the case or if's which add cyclic complexity.
Another benefit of the enum
is that it let you use the switch/case
syntax instead of infinite if/else
.
精彩评论