Page 528 - Introduction to Programming with Java: A Problem Solving Approach
P. 528

                494 Chapter 12 Aggregation, Composition, and Inheritance
In visualizing a card game, can you see two people holding cards and taking additional cards from a deck that sits between them? You should be able to see a deck, two hands, individual cards, and two people. For the deck, use a Deck class. For the two hands, use a Hand class. For the individual cards, use a Card class. You may or may not wish to represent the people. If you’re implementing an elaborate card game where players have personalities, use a Person class. Otherwise, there’s no need for a Person class. Let’s keep things simple and not implement a Person class.
In thinking about the big picture, you should ask yourself, “What is a game?” A game is a composition of several parts, so define Game as a whole class and define other classes as the parts of the game. A Game is composed of three components/parts—a deck and two hands. Thus, Deck and Hand are parts classes within the Game composition class. In Figure 12.17’s class diagram, note the association line connecting Game to Deck. The association line has a solid diamond, which indicates composition, and it has 1-to-1 multiplicity values, which indicate each game has one deck. The Game to Hand association line also has a solid diamond for composition, but it has 1-to-2 multiplicity values, which indicate each game has two hands.
Coming up with the idea of using a Game class is probably more difficult than coming up with the ideas for using Deck, Hand, and Card classes. Why? A game is non-tactile (that is, you can’t touch it), so it’s hard to see it as a class. Why bother with having a Game class? If you omit the Game class, you could still imple- ment a card game. Instead of declaring the deck and hand objects inside the Game class, you could declare them inside the main method. But it’s more elegant to put them inside a Game class. Why? By putting them inside a Game class, it furthers the goal of encapsulation. Also, it enables main to be streamlined. As you’ll
   GAroupOafCgardos PDF EnhanceCard 1*
 -cards : Card[] -currentSize : int
 +addCard(card : Card) : void +display() : void
 -num : int -suit : int
 +display() : void
     Deck
  +shuffle() : void +dealCard() : Card
 Hand
  +sort() : void +playACard() : Card
  12 11
  Game
 -deck : Deck -player1 : Hand -player2 : Hand
 +playAGame() : void
 Figure 12.17 Preliminary class diagram for Card Game program

















































































   526   527   528   529   530