I'm having trouble modeling my program to make use of polymorphism
Let's suppose we're writing a game, and there's a player that can have items in their inventory
so we have a List<Item> on the Player, seems reasonable to me
I want to model many subcategories of items, so suppose there are items that are weapons, and some items that are food items that the player can eat
So by using inheritance, we would have Weapon extends Item and Food extends Item, and everything works well until we need a weapon that you can eat, and so everything breaks and we need to use composition
So this is fine, we can refactor, decorate Item with mixins or interfaces such that it has methods now like .eat() and .attack().
The question now is, given that the player has a List<Item>, where each item has different behavior, how do I answer the question, does the player have any food, or does the player have any weapons? Or, want to open up a menu and show all the player weapons
I see the two options as, having a List<Food> alongside a List<Weapon> on the player, but then the edible weapon would be in both lists? Or a separate list? ... Or having to check each item to see whether it implements Attackable or is a Food, both of which don't make use of polymorphism.
Is there a nice way to model this?
Using JS + typescript if that matters
Aucun commentaire:
Enregistrer un commentaire