User
User

Reputation: 139

Would a Singleton be suitable in this case?

Imagine I have a class called FileManager. This class handles creating files and retrieving data from these files, along with loading and saving data from these files. This class will only ever need to have one instance. Should I use a Singleton to keep it as one instance (since that is all that is required) or should I just create a new instance each time?

I ask that you support your answer with a solid reason with facts.

EDIT: Here is an example using the Singleton. As an additional question, should this use eager or lazy instantiation? What would be the advantage to either and which is more acceptable in this case and in general?

public class FileManager {

private static FileManager instance;
private static File kitFile = null;
private static File langFile = null;

private static FileConfiguration langData = null;
private static FileConfiguration kitData = null;

public static FileManager getInstance() {
    if(instance == null)
        instance = new FileManager();
    if(kitFile == null)
        kitFile = new File(Kits.getInstance().getDataFolder(), "Kits.yml");
    if(kitData == null)
        kitData = YamlConfiguration.loadConfiguration(kitFile);
    if(langFile == null)
        langFile = new File(Kits.getInstance().getDataFolder(), "/lang/"+Kits.getInstance().getConfig().getString("lang"));
    if(langData == null)
        langData = YamlConfiguration.loadConfiguration(langFile);
    return instance;
}

The code goes on to have methods which create the files, save data to these files, and load data from these files. These methods are only called in one class. The code, then, goes on to have getters which are used throughout various classes.

Upvotes: 0

Views: 114

Answers (1)

firesurfing
firesurfing

Reputation: 155

I dont think its a good idea to implement a public getInstance method here. Is that a better way to implement some methods called "saveXXFile", "readXXFile" in this class? In that way, you can also avoid multithreading errors which may occur in your code.

In another word, if I write this, I may encapsulate some methods called "saveXXFile", "readXXFile" in this class rather than exposing the file instances to the class users.

Upvotes: 1

Related Questions