Design the data structure of a deck of cards

Design the data structures for a generic deck of cards. Explain how you would sub-class it to implement particular card games.

My initial thoughts:
The structure is clear here: a deck contains four suits and a suit contains 13 card. Each card has a numerical value from 1 to 13. If you think about a card game, different games differ from ways of dealing cards and putting cards back in. So we can have a set of abstract methods inside the class ‘Deck’ to allow sub-class implements its own way of dealing. The class diagram I draw is here:

Class Diagram for Card

Solution:

	public enum Suit {
		CLUBS(1), SPADES(2), HEARTS(3), DIAMONDS(4);
		int value;

		private Suit(int v) {
			value = v;
		}
	}

	public class Card {

		private int card;
		private Suit suit;

		public Card(int r, Suit s) {
			card = r;
			suit = s;
		}

		public int value() {
			return card;
		}

		public Suit suit() {
			return suit;
		}
	}

	public class BlackJackCard extends Card {
		public BlackJackCard(int r, Suit s) {
			super(r, s);
		}

		@Override
		public int value() {
			int r = super.value();
			if (r == 1)
				return 11; // aces are 11
			if (r < 10)
				return r;
			return 10;
		}

		boolean isAce() {
			return super.value() == 1;
		}
	}

Comments:

  1. Suit is just a label. It does not need to be a separate class therefore a enumeration class is enough.
  2. We don’t really need a wrapper class ‘Deck’ to be around a normal card.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: