Java – Pattern for Loading and Handling Resources

design-patternsjava

Many times there is the need to load external resources into the program, may they be graphics, audio samples or text strings.

Is there a patten for handling the loading and the handling of such resources?

For example: should I have a class that loads all the data and then call it everytime I need the data? As in:

GraphicsHandler.instance().loadAllData()
...//and then later:
draw(x,y, GraphicsHandler.instance().getData(WATER_IMAGE))
//or maybe
draw(x,y, GraphicsHandler.instance().WATER_IMAGE)

Or should I assign each resource to the class where it belongs?
As in (for example, in a game):

Graphics g = GraphicsLoader.load(CHAR01);
Character c = new Character(..., g);
...
c.draw();

Generally speaking which of these two is the more robust solution?

GraphicsHandler.instance().getData(WATER_IMAGE)
//or
GraphicsHandler.instance().WATER_IMAGE //a constant reference

Best Answer

I don't know that either option is going to be particularly robust. In both cases, you're relying on some kind of singleton or static-state-heavy implementation to manage what amount to global variables. How exactly you access the global variables (whether directly or hidden behind some kind of weakly typed "getData()" call) isn't going to matter a lot to maintainability in the face of a global variable scheme in general. Your application is going to be highly cross-coupled and interdependent either way.

I would say a decent option with an eye on future flexibility would be to take your getData() concept and put it in an interface. Then inject an instance of that interface into classes that need access to the data (and try to limit that number as much as possible). This way you can mock out or swap the thing that provides that data. The way you have it now, this is impossible -- every client of that singleton depends on the entire application state being spun up in order for it to be used, making testing and decoupling difficult, if not impossible. And that state of affairs is the opposite of robust.

Related Topic