要摆脱过多使用if条件的问题,可以尝试以下几种解决方法:
Animal animal;
if (type == "dog") {
animal = new Dog();
} else if (type == "cat") {
animal = new Cat();
} else if (type == "bird") {
animal = new Bird();
}
animal.makeSound();
public interface AnimalSoundStrategy {
void makeSound();
}
public class DogSoundStrategy implements AnimalSoundStrategy {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class CatSoundStrategy implements AnimalSoundStrategy {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
AnimalSoundStrategy soundStrategy;
if (type == "dog") {
soundStrategy = new DogSoundStrategy();
} else if (type == "cat") {
soundStrategy = new CatSoundStrategy();
}
soundStrategy.makeSound();
public class AnimalFactory {
public static Animal createAnimal(String type) {
if (type == "dog") {
return new Dog();
} else if (type == "cat") {
return new Cat();
} else if (type == "bird") {
return new Bird();
}
return null;
}
}
Animal animal = AnimalFactory.createAnimal(type);
animal.makeSound();
通过使用多态、策略模式或工厂模式,可以减少if条件的使用,使代码更加灵活、可扩展和易于维护。
上一篇:摆脱HTML元素-React
下一篇:摆脱警告和错误:R中的非语言对象