Is it good practice to often use instanceof?

前端 未结 6 1310
北海茫月
北海茫月 2020-12-14 11:44

The scenario. I\'m writting game-related code. In that game a Player(its also a class) has a list of Item. There are other types of items that inhe

6条回答
  •  执念已碎
    2020-12-14 11:47

    You should rethink your structure, instanceof in non-meta code is almost always a sign for an anti-pattern. Try to define the behaviour all Items have in common (like having a picture, a description and something happening when you click on them) in the Item-class/interface, making use of the abstract-keyword if appropiate, and then use polymorphism to implement the specifics.

提交回复
热议问题