Singletons and Factories are different things. To property construct a Singleton, I guess you could think of its getInstance() method as a factory. Factories make "things". Singleton means that there will only ever be 0 or exactly 1 of these "things" in existence at any time.
If you are trying to make a proper Singleton, it is surprisingly cumbersome to do this in a Thread-safe manner in Java. Without synchronization or other thread-safe countermeasures, the code you list above has a subtle race-condition around the check-then-set code to initialize ClientFactory instance variable. There are two ways around this race-condition. Which way you pick is largely gated by how expensive it is to go through the ClientFactory constructor. My constructors are typically lightweight, so I go the path of avoiding the need for synchronization all together.
public class ClientFactory {
private static final ClientFactory instance = new ClientFactory();
private ClientFactory() { }
public static ClientFactory getInstance() {
return instance;
}
}
If you want to be "lazy" in the construction, not building on until someone explicitly calls getInstance(), now synchronization is needed to avoid the race condition.
public class ClientFactory {
private static ClientFactory instance = null;
private ClientFactory() { }
public static synchronized ClientFactory getInstance() {
if ( instance == null ) {
instance = new ClientFactory();
}
return instance;
}
}