SpriteCache manager in the SpaceInvaders game

I’ve been going through this SpaceInvader tutorial, and it seems to be very badly designed.

For one thing, there is this SpriteCache class, that extends on ResourceCache (in case you have AudioCache manager also).

The thing is that each time I call spriteCache.getSprite(“imagename.png”); it returns me a new object! This is a big overhead since I only need one instance of the image to exist.
So if I have the same 6 sprites on the screen, then the file is only loaded 1 time, but 6 instances of the image exist.
I want this to be so that if there were no matter how many sprites on the screen, then the sprite should only be loaded once, and only one instance exist … just painted at different locations.

Any good SpriteCache (manager) out there that I can use? Or any ideas how to solve this?

I think you are mistaken. (you are refering to this right: http://www.planetalia.com/cursos/index.jsp)
The image is only loaded if it doesnt already exist in the hashtable, otherwise it is just gotten out of the hashtable.

Oh yes, that’s the game I’m referring to.

The problem with that game is that it creates a new image for each call to getSprite() … while it only loads the file once, it creates the image n times for n calls to getSprite() … it in fact should cache the image, and not the file.

I solved the problem.

I changed the getSprite method in SpriteCache class.

Added member var:

private HashMap imageResources = new HashMap();
	public BufferedImage getSprite(String name) {
		if(imageResources.containsKey(name)) return (BufferedImage)imageResources.get(name);
		
		BufferedImage loaded = (BufferedImage)getResource(name);
		BufferedImage compatible = createCompatible(loaded.getWidth(),loaded.getHeight(),Transparency.TRANSLUCENT); 
		Graphics g = compatible.getGraphics();
		g.drawImage(loaded,0,0,this);
		
		imageResources.put(name,compatible);
		return compatible;
	}