gpt4 book ai didi

java - 使用多态性进行代码重构

转载 作者:行者123 更新时间:2023-12-02 06:02:54 26 4
gpt4 key购买 nike

有基类和一些从它派生的类Child1、Child2、Child3等。给定代码:

    Base object;
String data = ...;

switch(data) {
case "Child1" :
object = new Child1();
break;
case "Child2" :
object = new Child2();
break;
case "Child3" :
object = new Child3():
break;
default:
object = null;
break;
}

如果可能的话,知道如何重构它吗?

最佳答案

尝试(未经测试):

public enum BaseType{
CHILD_1("Child1"){
@Override
public Base createBase(){
return new Child1();
}
},
CHILD_2("Child2"){
@Override
public Base createBase(){
return new Child2();
}
},
CHILD_3("Child3"){
@Override
public Base createBase(){
return new Child3();
}
};
private static final Map<String, BaseType> TYPES = new HashMap<>();

static {
for(BaseType type : values()){
TYPES.put(type.name, type);
}
}

private final String name;

protected BaseType(String name){
this.name = name;
}

public abstract Base createBase();

public static BaseType getBaseType(String name){
return TYPES.get(name);
}

}



Base base = null;
String data = ...;
BaseType baseType = BaseType.getBaseType(data);
if (baseType != null){
base = baseType.createBase();
}

关于java - 使用多态性进行代码重构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22535581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com