javadesign-patternssingletonanti-patternsmultiton

How to create many singleton instances for a generic class?


I have such code:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileManager<T> {

    private final File file;

    private FileManager(String property) throws IOException {
        this.file = new File(ConfigReader.getProperty(property + ".file.path")
                .orElseThrow(() -> new IOException(property + " file path is not specified in application.properties.")));
    }

    public void saveToFile(List<T> list) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    private List<T> loadFromFile() {
        if (file.exists()) {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
                return (List<T>) ois.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return new ArrayList<>();
    }

}

And I have also two classes (ex. Manufacturer, Product), objects of which i need to serialize and deserialize. Basically it's the same code for these classes, so I came up with this generic class idea. I think it would be better if there were two and only two instances for two of my classes.

So, singleton pattern is not quite suitable here. The only solution I came up with is to use multitone pattern, but I think it may be quite bad. Are there any patterns or better solutions for this situation? Maybe I should consider to redesign this class or smth? What is the best to do here?


Solution

  • You could create a base class where you would inherit Manager and Product from, so you will not duplicate your code and you can apply the singleton patter for the subclasses, maybe have the base class instantiate its subclasses and then you are all set.