Reputation: 189
I am a programmer beginner (more or less), and I was wondering what is the best way to load resources(bmps, mp3s, and so on) in Android or java in general . What I mean is that I make a class that will hold other static classes that will hold my resources(so I don't need to pass parameters when i use them, the resources can be loaded with ease and unloaded just as easy). Something like this.
public class ResourcesHandler {
public static Context mContext;
public static GraphicsCollection mGraphics;
public static SoundFxPlayer mSoundFx;
public static MusicPlayer mMusic;
public static void unload() {
mContext=null;
mGraphics.unload();
mSoundFx.unload();
mMusic.unload();
}
}
It probably sounds like a stupid question, but I ask mostly because I never saw something like this from someone else. I saw only resources passed back and forth or they're loaded where they need to be used. What do you think? What is the best practice?
Upvotes: 1
Views: 104
Reputation: 5176
For accomplishing that best way would be to use Singleton pattern since you are gonna need your Resources all the time throughout the application life cycle. Creating a Singleton class is as follows :
Static member : This contains the instance of the singleton class.
Private constructor : This will prevent anybody else to instantiate the Singleton class.
Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.
Also take care of of multi-threaded environment if that exists in your case.
public class ResourcesHandler {
private static ResourcesHandler handlerObj;
private Context mContext;
private GraphicsCollection mGraphics;
private SoundFxPlayer mSoundFx;
private MusicPlayer mMusic;
private ResourcesHandler(){
//TODO
}
public static ResourcesHandler getInstance() {
if (handlerObj == null){
handlerObj = new ResourcesHandler();
}
return handlerObj;
}
public void unload(){
mContext=null;
if(null != mGraphics){
mGraphics.unload();
}
if(null != mSoundFx){
mSoundFx.unload();
}
if(null != mMusic){
mMusic.unload();
}
}
}
Upvotes: 2
Reputation: 412
In java in general your approach looks good enough although a lot depends on the type of program and resources you are using.
In android however, I am not convinced about your approach. Reason being that in android resources are already segregated into resources directory. and resource initialization is a lot different. Also the flow of activities would make it difficult to use this approach.
Upvotes: 0