我有类Dog,Cat,... 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();
break;
case 1:
pet1 = new Dog();
break;
.....
}
}
public void pet2Init(){
switch (i){
case 0:
pet2 = new Cat();
break;
case 1:
pet2 = new Dog();
break;
.......
}
}
}
答案 0 :(得分:0)
我会给你一个不改变设计的解决方案,看看它有多尴尬:
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;
}
更清洁的解决方案使用Map<Integer, Supplier<Pet>>
:
private Map<Integer, Supplier<Pet>> map = Map.of(0, Cat::new, 1, Dog::new);
private Supplier<Pet> getPet() {
return map.getOrDefault(i, Cat::new);
}
尽管如此,它仍然不清楚你想要实现的目标。这些变量可以在单个方法中初始化,因为它们共享相同的算法:
public void initialisePets(){
final Supplier<Pet> supplier = getPet();
pet1 = supplier.get();
pet2 = supplier.get();
}