如何在使用继承时摆脱instanceof检查?

Jav*_*per 4 java oop inheritance design-patterns

假设我们有一个类Animal,子类为cat,eagle

现在我有一个方法:

public void process(Animal animal) {

   if (animal instanceof Cat) {
     if (!animal.meow()) {
        throw exception("cat does not meow");
     } else {
      animal.feedFish();
     }
   }

   if (animal instanceof eagle) {
      if (!animal.fly()) {
         throw exception("eagle does not fly");
      } else {
        animal.checkMaxFlightAltitude();
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

这里的猫有2种方法meowfeedfish这比鹰的方法完全不同fly,并checkmaxflight

大多数设计模式都围绕着假设,即子类有一个常见的方法,比如draw()由circle draw和square 继承的Shapedraw

  1. 有没有办法对子类进行验证,例如没有instanceof检查的猫和老鹰?

  2. 任何好的设计模式(假设子类不共享基类中的方法?)

ass*_*ias 7

您可以在子类中使用抽象process方法Animal并实现它:

class Animal {
  protected abstract void process();
  public static void process(Animal a) { a.process(); }
}

class Cat {
  void process() {
    if (!meow()) throw exception("cat does not meow");
    else feedFish();
  }
  public boolean meow() { ... }
  public void feedFish() { ... }
}
Run Code Online (Sandbox Code Playgroud)