instanceof keyword usage

后端 未结 8 2415
死守一世寂寞
死守一世寂寞 2021-02-14 10:21

Is using the instanceof keyword against the essence of object oriented programming? I mean is it a bad programming practice? I read somewhere that us

8条回答
  •  星月不相逢
    2021-02-14 10:58

    How about in the case of a creation factory (See below)? In this case, I don't think it is appropriate for an Animal subclass to know how to build a cage for itself. It seems out of out of scope of what an Animal is and forces the Animal subclass to take on behaviors that are not intrinsic to what an Animal is.

    public static Cage createCage(Animal animal) {
      if (animal instanceof Dog)
        return new DogHouse();
      else if (animal instanceof Lion)
        return new SteelCage();
      else if (animal instanceof Chicken)
        return new ChickenWiredCage();
      else if (animal instanceof AlienPreditor)
        return new ForceFieldCage();
      ...
      else
        return new GenericCage();
    }
    

提交回复
热议问题