I just come across this code and find it interesting to know whether you consider this as another single instance pattern?
public class Initiator
{
private static String str;
// there is many more private field here...
private static String getMethod() { ... }
// there is many more private getter here...
static
{
// initialize all field here...
}
}
The programmer claim that by doing this I can ensure there is always one instance in the memory. Notice there is no setter method in the code as the programmer did the initialization work in static code block. And I never notice the static code block can be use in such a way.
0
It’s a valid usage, I tend to use the static block when the initialization may throw checked exceptions:
private static final Cipher cipher;
static{
try{
cipher = Cipher.getInstance("AES");
//initialization which may throw
}catch(Exception e){
throw new RuntimeException(e);//rethrow as unchecked if it fails -> will stop the program with visible stacktrace
}
}
1