开发者

Create table class as a singleton

I got a class that I use as a table. This class got an array of 16 row classes. These row classes all have 6 double variables. The values of these rows are set once and never change.

Would it be a good practice to make this table a singleton? The advantage is that it cost less memory, but the table will be called from multiple threads so I have to synchronize my code which way cause a bit slower application. However lookups in this table are probably a very small portion of the total code that is executed.

EDIT: This is my code, are there better ways to do this or is this a good practice? Removed synchronized keyword according to recommendations in this question.

final class HalfTimeTable {
    private HalfTimeRow[] table = new HalfTi开发者_C百科meRow[16];
    private static final HalfTimeTable instance = new HalfTimeTable();

    private HalfTimeTable() {
        if (instance != null) {
            throw new IllegalStateException("Already instantiated");
        }
        table[0] = new HalfTimeRow(4.0, 1.2599, 0.5050, 1.5, 1.7435, 0.1911);
        table[1] = new HalfTimeRow(8.0, 1.0000, 0.6514, 3.0, 1.3838, 0.4295);
        //etc
    }

    @Override
    @Deprecated
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException(); 
    }

    public static HalfTimeTable getInstance() {
        return instance;
    }

    public HalfTimeRow getRow(int rownumber) {
        return table[rownumber];
    }
}


It depends entirely on how your class is going to be used. You only want to make it a singleton if you are absolutely sure that you want exactly one instance (per JVM) at any time.

Unfortunately, without knowing the details of what your code is doing it's impossible to give a definitive answer.

Would you ever want two different tables? You say that the data in a table never changes, but would you ever create two tables containing different data? If so, a singleton is not appropriate. If you're sure you only want one instance then a singleton is fine.


The values of these rows are set once and never change.

Yes singleton is good idea in this case but why do you synchronize even though it is read only ?


You do not have to implement the singleton pattern to share an object between clients. You can create it once and pass to the other objects during construction.

If with The values of these rows are set once and never change you mean that the table and its values is constructed completely before its use by its client, you have read-only access to the information. This would mean no synchronisation is needed.


As org.live.java said - if you for example initialize the table in its constructor (NOT lazy) then there is no reason to synchronize

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜