It seems to me that this is often encountered in practice and I was wondering if there is a design pattern for the following:
Suppose I have a class that represents a card:
public class Hand {
private static Random rng;
private Rank rank;
private Suit suit;
public Hand() {
if (prng == null)
prng = new Random();
}
//more stuff
}
}
Every time I instantiate a Card, I want a random card. Doing it the above way wastes one comparison to null per instantiation. If I create a static field and allocate it in the deceleration:
private static Random rng = new Random();
a new Random object gets instantiated every time - also not very efficient.
If I pass the Random object into the constructor, I violate "tell, don't ask."
Perhaps there is another suggestion, but so far, I think the best way is the null check.
a new Random object gets instantiated every time - also not very efficient.
that's incorrect, astatic
field will only be initialized once for all instances of that type.