-
Notifications
You must be signed in to change notification settings - Fork 153
/
Card.java
79 lines (71 loc) · 1.9 KB
/
Card.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*******************************************************************************
* Companion code for the book "Introduction to Software Design with Java"
* by Martin P. Robillard.
*
* Copyright (C) 2019 by Martin P. Robillard
*
* This code is licensed under a Creative Commons
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
*
* See http://creativecommons.org/licenses/by-nc-nd/4.0/
*******************************************************************************/
package chapter4;
/**
* Implementation of a playing card. This class yields immutable objects.
* This version of the class shows an application of the Flyweight design
* pattern where the flyweight store is pre-initialized.
*/
public class Card
{
// Flyweight store
private static final Card[][] CARDS = new Card[Suit.values().length][Rank.values().length];
private final Rank aRank;
private final Suit aSuit;
// Initialization of the flyweight store
static
{
for( Suit suit : Suit.values() )
{
for( Rank rank : Rank.values() )
{
CARDS[suit.ordinal()][rank.ordinal()] = new Card(rank, suit);
}
}
}
// Private constructor
private Card( Rank pRank, Suit pSuit)
{
aRank = pRank;
aSuit = pSuit;
}
/**
* @param pRank The rank of the requested card.
* @param pSuit The suit of the requested card.
* @return The unique Card instance with pRank and pSuit
* @pre pRank != null && pSuit != null
*/
public static Card get(Rank pRank, Suit pSuit)
{
assert pRank != null && pSuit != null;
return CARDS[pSuit.ordinal()][pRank.ordinal()];
}
/**
* @return The rank of the card.
*/
public Rank getRank()
{
return aRank;
}
/**
* @return The suit of the card.
*/
public Suit getSuit()
{
return aSuit;
}
@Override
public String toString()
{
return String.format("%s of %s", aRank, aSuit);
}
}