简体   繁体   中英

Avoid using instanceOf in observer method

I have the following system in Java:

public class Human {
     public void drown(Animal animal) {
          if (animal instanceOf Fish) {
              return;
          } else {
              animal.die();
          }
     }
}

public abstract class LandAnimal extends Animal{...}
public class Tiger extends LandAnimal{...}

public abstract class Fish extends Animal {...}
public class Trout extends Fish {...}

I have thought of adding a method

public abstract boolean drownable() {...}

in class Animal but I don't have access to the code of Animal class. As I know the use of instanceOf is considered bad OOP practice. How do I avoid the use of instanceOf in this case? Thanks.

The drown() method in Human should be (by the way, why do humans want to drown animals?):

 public void drown(Animal animal) {
      animal.drown();
 }

And each Animal will know what to do, for example:

// in class Tiger
public void drown() {
    die();
}

// in class Fish
public void drown() {
    // do nothing, fish can't drown
}

You would declare Animal.drown() and override it in Fish , containing the appropriate 'kill code' :). So you'd just need to call drown() on each animal and each instance will behave according to its type specific method implementation.

public class Human {
     public void drown(Animal animal) {
         animal.drown();
     }
}

Methods can be overloaded based on their arguments. You can have two different methods:

public void drown(Fish f) {
  return;
}

public void drown(LandAnimal a) {
  a.drown();
}

However, it should be noted that this makes determining whether some animal will drown the responsibility of the Human class, which, as other answers show, is arguable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM