I was wondering if my code will produce a true singleton. I am creating an Android app, and all activities should access my API through one instance of the SyncApi
class.
public class Api {
private static SyncApi api = null;
static {
synchronized (api) {
if (api == null) {
api = new ApiFActory().getSyncApi();
}
}
}
public static SyncApi getInstance() {
return api;
}
}
Use of the class would look like:
SyncApi api = Api.getInstance();
api.logOn("jjnguy", "pa55w0rd");
SyncApi
instance directly in the declaration? No need for thestatic
constructor. Java guarantees that initialisation of static members will only happen once. \$\endgroup\$