de3
de3

Reputation: 2000

Class for storing data in java, simulating a mysql table

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.

Upvotes: 0

Views: 1286

Answers (2)

brian_d
brian_d

Reputation: 11385

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.

Upvotes: 1

Matt D.
Matt D.

Reputation: 214

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

}

Upvotes: 1

Related Questions