Create table class as a singleton
Posted
by
Mark
on Stack Overflow
See other posts from Stack Overflow
or by Mark
Published on 2010-12-31T15:04:08Z
Indexed on
2010/12/31
15:54 UTC
Read the original article
Hit count: 160
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 HalfTimeRow[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];
}
}
© Stack Overflow or respective owner