I do recognize that this question has been asked many times before, but I can't get the answer I want out of it. And that question is, "Should I use a singleton or a class with all static members and methods?"
I only ever need one instance for what I am trying to achieve and both ways can work equally well. So designwise, is there a better way to do it? Or should I use either at all?
I am trying to write a "database" class for my program. This "database" uses other objects to store and organize the data. However the database itself sorts and searches the data. And given that it is a database, I only want one instance of it. I don't want to have to access multiple places for data. The database itself handles that.
Note- I already wrote it as enum Data.BASE
. It uses method handle(String)
to take a string command and manipulate the data within it by calling other methods. Should I have wrapped Data.BASE
in a "static class" and used that to talk to Data.BASE
? (I commuicate directly with Data.BASE
)
I have am planning on making a class that is meant to load and save settings from my program called SettingsManager
. It would use, not implement Savable
interface to manipulate objects with savable settings. SettingsManager
would be called when the program is begun and ends. However, it can only manipulate objects that are added to it (SettingsManager.add(Savable)
). Just like the first case, I don't need multiple instances of it. I only want one instance keeping track of writing and saving preferences.
Is there a better way of going about this that I can't think of?
I do recognize that this is not a specific coding question. However, I feel that these are important design and stylistic questions that I will certainly need to reference in the future for other programs.
For the first case, if it is just one instance at any given time in your JVM then make it final static; this is faster.
For the second case, if SettingsManager
is manipulating data in the database, then you can do the dependency injection and let the framework decide when to initiate and destroy it.
The information you provided is not much so I cannot tell you exactly what is better. For example, if we knew you are using Java EE or Java SE or if you are using any framework (like Spring - SpringMVC) that would help us to give you better advice.