简体   繁体   中英

C# Design Regarding Static Classes and Inheritence

I am designing a card game in C#. Each card is an instance of the Card class that contains two properties: a unique ID for the card and a reference to a CardData object. The object of type CardData implements the methods regarding how the Card functions within the game rules. Many cards (ex. if there are multiple jack of clubs) can reference the same card data.

public class Card {
    public int id;
    public CardData card;
}

My question is regarding how I should implement the CardData class. My first instinct was to design an abstract base class CardData with a bunch of methods like WhenPlayed() and WhenRemoved() , and then have a subclass for each card that implements them.

public abstract class CardData () {
    public abstract void WhenPlayed();
    public abstract void WhenRemoved();
}

public class JackOfClubs : CardData () {
    public override void WhenPlayed()  { 
        Console.WriteLine( "You played a Jack of Clubs!" );
    }
    public override void WhenRemoved() {
        Console.WriteLine( "Bye for now" );
    }
}

However, since I never want to actually instantiate a JackOfClubs object, but rather instantiate Card s and give them a reference to the JackOfClubs class, it would make sense to make the CardData class and all subclasses static . This creates a problem, because as far as I know static classes cannot inherit.

Furthermore, I considered using an interface but I wanted the possibility of default methods. For instance, if 90% of my CardData objects implement WhenRemoved() as "Bye for now", it would be tiresome to retype that for each subclass. I could use a non abstract CardData class to achieve this, but not an interface.

My question is what would be the best or correct approach to handling a class structure such as this, if there is one.

I would do a design like this please refer the diagram , so that you don't create as many classes as there are many cards, essentially they are different objects of the same class. So we have factory that holds a custom collection called Cards which is a collection of Card class that has a type and value. You can implement the play method depending on the type and value o the card. In the case that you are playing a game where all the cards are not involved, this design just works fine, in the case that you are extending this to multiple card games, if you add one more class card category, this design encompasses that as well. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM