vendredi 29 novembre 2019

Changing method behaviour depending on subtype of 2 input parameters

I am trying to create a card game with a clean class design. I would like to compare 2 cards and return the one with the highest "value".

I have an abstract card class and 2 classes inherited from it :

public abstract class Card {...}
public class ColoredCard extends Card {...}
public class TrumpCard extends Card {...}

I would like to use a compare method, which would have different implemented logic depending on subtypes of the card, like that (I put those method within an external "Comparator" class :

public Card compare(ColoredCard card, TrumpCard card2) { //implementation for 1st subtype combination
public Card compare(ColoredCard card, ColoredCard card2) { //implementation for 2nd subtype combination
//other type combinations

But it throws a compilation error whenever I call it from my Cards classes :

//within any my card subclass
public Card compareTo(Card c) {
    return Comparator.compare(this, c); //compilation error because it cant determine "c" variable subtype

What design would you recommend for that purpose ? Is there a convenient solution to that problem ?

I would like to avoid to use instanceOf instruction or reflection if possible.

Thank you,

Aucun commentaire:

Enregistrer un commentaire