简体   繁体   中英

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 change 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.

enum另一个好处是它允许你使用switch/case语法而不是无限if/else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM