0

I want to create deck of cards using a for loop and my Factory class method. I have setup the suit and face values as enums. How should i aproach this?

public static class FactoryClass {
    public static Card CreateCard(CardFace face, CardSuit suit) {


        return new Card(face, suit);
       
    }


 
}



    public enum CardFace {
    A, _2, _3, _4, _5, _6, _7, _8, _9, _10, J, Q, K
}



   public enum CardSuit {
    Spades, Hearts, Clubs, Diamonds
}

 public void Deck() {
      

        for (int i = 0; i < 13; i++) {
            for (int j = 0; j < 4; j++) {
                _cards.Add(FactoryClass.CreateCard();
            }
        }
    }

1 Answers1

0

Not strictly related to the question you asked, but I'm not really sure of the value for having a factory just for creating a playing card. I see more value in having a factory however for creating a deck of cards.

Given

public enum CardFace
{
    A, _2, _3, _4, _5, _6, _7, _8, _9, _10, J, Q, K
}

public enum CardSuit
{
    Spades, Hearts, Clubs, Diamonds
}

public class Card 
{
    public CardFace Face { get; set; }
    public CardSuit Suit { get; set; }

    public Card(CardFace face, CardSuit suit)
    {
        Face = face;
        Suit = suit;
    }
}

That this is how you represent a card, you can create a factory to create a sorted deck of cards in the following way:

public static class CardFactory
{
    public static IEnumerable<Card> CreateDeck()
    {
        foreach (CardFace face in Enum.GetValues(typeof(CardFace)))
        {
            foreach (CardSuit suit in Enum.GetValues(typeof(CardSuit)))
            {
                yield return new Card(face, suit);
            }
        }
    }
}
Hayden
  • 2,902
  • 2
  • 15
  • 29