I realise that it’s generally a bad idea to put objects of different types into one collection, and that I can do it by making the type be “object”, but I have a situation where I can’t think of an alternative, and was hoping someone else could.
Situation:
At the end of a turn in a game I would like the player to effectively pick up a card from a deck. The card will be one of three types of card. Usually the card will go into the player’s hand and allow the player to perform a standard action, but I want there to be a chance of the player getting a special card, with its action being specific to that card, and there to be a chance of the player getting a card which takes its action immediately rather than going into the player’s hand. These types cards have nothing in common, so it doesn’t seem to make sense to have a common interface, but I want them to be randomly mixed through the deck, so I’d like to have them all in one collection.
Does anyone have any design suggestions? (I’m rather new to OO design)
Your idea of using an interface was on the right track. However, you don’t need to make the “special action card” implement a
Cardinterface: make a different interface for it (say,Deckable), make theCardinterface inherit it, and then implement that interface in your “special action card” class.Now you can create a list of
Deckable, and mix your special cards into it: