Java 如何消除initmethod中的重复代码
我有狗、猫。。。扩展了Pet和init方法。如果init方法必须无效,如何消除重复代码Java 如何消除initmethod中的重复代码,java,code-duplication,Java,Code Duplication,我有狗、猫。。。扩展了Pet和init方法。如果init方法必须无效,如何消除重复代码 public class Tester { private Pet pet1; private Pet pet2; private int i; public void pet1Init(){ switch (i){ case 0: pet1 = new Cat(); br
public class Tester {
private Pet pet1;
private Pet pet2;
private int i;
public void pet1Init(){
switch (i){
case 0:
pet1 = new Cat();
break;
case 1:
pet1 = new Dog();
break;
.....
}
}
public void pet2Init(){
switch (i){
case 0:
pet2 = new Cat();
break;
case 1:
pet2 = new Dog();
break;
.......
}
}
}
我将为您提供一个解决方案,不改变您的设计,看看它有多尴尬:
public void pet1Init(){
pet1 = getPet().get();
}
public void pet2Init(){
pet2 = getPet().get();
}
private Supplier<Pet> getPet() {
Supplier<Pet> supplier = Cat::new; // default pet
switch (i){
case 0:
supplier = Cat::new;
break;
case 1:
supplier = Dog::new;
break;
}
return supplier;
}
public void pet1Init(){
pet1=getPet().get();
}
公共无效pet2Init(){
pet2=getPet().get();
}
私人供应商getPet(){
供应商=猫::新;//默认宠物
开关(一){
案例0:
供应商=类别::新;
打破
案例1:
供应商=狗::新;
打破
}
退货供应商;
}
稍微干净一点的解决方案使用映射
:
private Map=Map.of(0,Cat::new,1,Dog::new);
私人供应商getPet(){
return map.getOrDefault(i,Cat::new);
}
尽管如此,我们仍然不清楚你想要实现什么。这些变量可以在单个方法中初始化,因为它们共享相同的算法:
public void initialisePets(){
final Supplier<Pet> supplier = getPet();
pet1 = supplier.get();
pet2 = supplier.get();
}
public void initialisePets(){
最终供应商=getPet();
pet1=supplier.get();
pet2=supplier.get();
}
您可以添加一个私有静态Pet create(int i){…}
方法。@BenWatson,pet1
和pet2
将如何初始化(如果它们作为参数传递)?@BenWatson Java是。因此,不能通过将参数传递到方法来初始化参数。
public void initialisePets(){
final Supplier<Pet> supplier = getPet();
pet1 = supplier.get();
pet2 = supplier.get();
}