如何为泛型类创建多个单例实例?

问题描述 投票:0回答:1

我有这样的代码:

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<>();
    }

}

我还有两个类(例如制造商、产品),我需要序列化和反序列化它们的对象。基本上这些类的代码是相同的,所以我想出了这个通用类的想法。我认为如果我的两个类有两个且只有两个实例会更好。

所以,单例模式在这里不太合适。我想出的唯一解决方案是使用多音模式,但我认为这可能很糟糕。对于这种情况有什么模式或更好的解决方案吗?也许我应该考虑重新设计这个类或其他东西?在这里最好做什么?

java design-patterns singleton anti-patterns multiton
1个回答
0
投票

您可以创建一个基类,从中继承

Manager
Product
,这样您就不会重复代码,并且可以为子类应用单例模式,也许让基类实例化其子类,然后您就可以了一切就绪。

© www.soinside.com 2019 - 2024. All rights reserved.