避免对类似类型的检查使用if条件,可以使用多态或者设计模式来解决这个问题。以下是两种常见的解决方法:
abstract class Animal {
// 公共方法
public abstract void makeSound();
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
// 不需要使用if条件进行检查
dog.makeSound(); // 输出: Dog barks
cat.makeSound(); // 输出: Cat meows
}
}
在上面的示例中,Animal是一个抽象类,Dog和Cat是其子类。通过将Dog和Cat对象声明为Animal类型,我们可以在不使用if条件检查的情况下调用它们的公共方法makeSound()。
interface Animal {
void makeSound();
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
class AnimalFactory {
public Animal createAnimal(String type) {
if (type.equalsIgnoreCase("Dog")) {
return new Dog();
} else if (type.equalsIgnoreCase("Cat")) {
return new Cat();
}
return null;
}
}
public class Main {
public static void main(String[] args) {
AnimalFactory factory = new AnimalFactory();
Animal dog = factory.createAnimal("Dog");
Animal cat = factory.createAnimal("Cat");
if (dog != null) {
dog.makeSound(); // 输出: Dog barks
}
if (cat != null) {
cat.makeSound(); // 输出: Cat meows
}
}
}
在上面的示例中,Animal是一个接口,Dog和Cat是其实现类。AnimalFactory是一个工厂类,根据传入的类型参数创建相应的Animal对象。通过使用工厂模式,我们可以根据类型创建对象,而不需要使用if条件进行检查。
上一篇:避免堆空间问题-线程