I've already read some questions about the disadvantages of static variables (for example why are static variables considered evil, but i find some difficulties in choosing the best solution to avoid to use them.
In my simple chess application, for example, i have an abstract class, Piece, with many subclasses. Every Piece must have a BufferedImage variable, image, but i want to load every image just one time for each Piece.
This would be very easy by using static variables, something like that :
abstract class Piece
{
// ...
public abstract BufferedImage getImage();
}
class Bishop extends Piece
{
private static final BufferedImage image = null;
static{
try{
image = ImageIO.read(ClassLoader.getSystemResource("chess/img/pieces/Bishop.png"));
}
catch(IOException ex){
// ...
}
}
public BufferedImage getImage(){
return image;
}
}
Of course this code doesn't follow OOP, and inheritance is not used for the image variable.
A solution would be to load all the images in an external class, and let all the subclasses instances to keep the reference to the same object:
abstract class Piece
{
final BufferedImage image;
public Piece(/* ... */ BufferedImage image){
this.image = image;
}
public BufferedImage getImage(){
return image;
}
}
class Bishop extends Piece
{
public Bishop(/* ... */ BufferedImage image){
super(/* ... */ image);
// ...
}
}
But what if i need to create the subclasses instances from n different classes ? The images would be loaded at least n times, assuming i create just one instance of those n classes.
I've considered to keep the images reference in a Singleton pattern designed class, but i also want to keep the image variable in the Piece class to simply use the getImage() method for every Piece.
Is it a good design to use the second solution combined with the Singleton pattern, so i would pass to every Piece's subclass constructor the reference to the same BufferedImage obtained with a method like SingletonClass.getXxxImage()?
Or is there any better approach? Of course it would be not so evil to load a BufferedImage more than one time, but i would like to have a general solution to avoid useless repetitions of code.
Thanks for your help !