Java – using enum or string as static factory methods?

Would it be better to schedule to the correct object using enum or string to create it in a static factory method?

String example:

public static Car createCar(String carName){
    if(carName.equals("Ferrari")){
        return new Ferrari();
    }
    else if(carName.equals("Porsche")){
        return new Porsche();
    }
    ....
}

Enumeration example:

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, as far as I say:

Benefits of using enumeration:

>Avoid users calling factories with unprocessed carname

Disadvantages of using enum:

Dependency is increased because changing to enumeration (for example, Ferrari to enzo_ferrari) will need to be modified on the client However, using string, we can redirect Ferrari to Enzo Ferrari instance without recompiling the client code Of course, we can do the same thing for the client using the old enumeration value and Ferrari redirecting to the enzo-ferrari enumeration, but to me, it means that the enumeration must keep the old value for client compatibility... It doesn't make sense to me

I'd like to know what you think of this problem?

Solution

If, as in this case, there are a certain number of acceptable parameters for the method, it is best to enforce the constraint on the client of the method as much as possible In this case, accepting any old string will result in more failures than using enumeration

However, in this limited case, you may also consider using the naming factory method for each type of vehicle: e.g. createferrari(), createporsche(), etc

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>