0

I want to use a class in Java for storing data which can be accessed for all other classes. Just like if it was a Mysql table.

This class should have only one instance, this way whenever its content is changed, all classes see the same content.

What is the best way to do it? I have read about the singleton pattern, but I don't know if it would be a design error to use it.

2 Answers 2

1

Create a singleton class with a data structure that meets your needs (Map, or List, or combo). Like so (example was just handcoded, dont know if it will compile):

public class FakeTable {
    private Map vals = new HashMap();
    private static final FakeTable INSTANCE = new FakeTable();
    private FakeTable() {}   // Private constructor
    public static FakeTable getInstance() {
        return INSTANCE;
    }

    public void setValue(String col, Object val) {
        vals.put(col, val);
    }

    public Object getVal(String col) {
        return vals.get(col);
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

Either have the data accessible as a static member or use a singleton. I would extend TableModel. TableModel is designed well already, and you can display your data easily in a JTable later if you wish.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.