简体   繁体   中英

How to have one function create multiple different types of the same class

I want to make a deck of 16 cards, with a number of each type of card in the deck.

This is my current solution but it does not look good.

How do I make it more clean and make it follow OOP Principles.

Each of the pieces(guards,priests,etc) inherits from the Card Class.

Is Generic types something I should be looking at here?

Code image with formatting

 class Deck
{
    public List<Card> Cards;
    int NumberofGuards = 5;
    int NumberofPriests = 2;
    int NumberofBarons = 2;
    int NumberofMaids = 2;
    int Numberofprinces = 2;
    int NumberofKings = 1;
    int NumberofCountesses = 1;
    int NumberofPrincesses = 1;
    public Deck()
    {
        //Guards
        for (int i = 0; i < NumberofGuards; i++)
        {
            Cards.Add(new Guard());
        }
        //Priests
        for (int i = 0; i < NumberofPriests; i++)
        {
            Cards.Add(new Priest());
        }
        //Barons
        for (int i = 0; i < NumberofBarons; i++)
        {
            Cards.Add(new Baron());
        }
        //maids
        for (int i = 0; i < NumberofMaids; i++)
        {
            Cards.Add(new Maid());
        }
        }
    }

}

abstract class Card
{
    public string Name { get; set; }
    public int Number { get; set; }
    public abstract void Keep();
    public abstract void Discard();
    public abstract void Use();
}

This would be a good use for a factory pattern implementation.

public class CardFactory<T> where T : Card, new()
{
    public static List<T> BuildMany(int count) {
        var list = new List<T>();
        for (int x=0; x<count; x++)
        {
            list.Add(new T());
        }
        return list;
    }
}

Then, modify your Deck class to use it:

public class Deck

{
    public readonly List<Card> Cards;
        
    public Deck(int numberOfGuards) // [numberOfPriests, etc]
    {
        // Guards
        Cards.AddRange(CardFactory<Guard>.BuildMany(numberOfGuards));

        // [...]
    }
}

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