Let’s assume that I have 3 classes: JSONReader, Configuration, Worker.
With JSONReader I setting up the fields of Configuration.
With Worker I getting data of fields from Configuration.
So here the example of reader…
public class JSONReader {
//Read json file and it's data...
Configuration config = Configuration.getInstance();
config.getInstance().setURISource(reader.get("uriSource"));
}
Here’s my configuration class
public class Configuration{
private Configuration(){}
private static Configuration instance = null;
private final String uriSource;
public static synchronized Configuration getInstance()
{
if (instance == null)
instance = new Configuration();
return instance;
}
public String setURISource(String uri){
this.uriSource = uri;
}
public String getURISource(){
return uriSource;
}
}
Here the worker…
public class Worker {
\\Doing some stuff, at certain point I need to get the data..
Connection connection = new Connection();
connection.setConnection(Configuration.getInstance().getURISource()/*and other data*/);
}
I used the approach of singleton, verified the hashcode getting an instance of Configuration in my reader and worker…hashcodes returns the same value.
But, getters are null the same as variables are null after being set them in my reader.
Any suggestions? Ideas?
>Solution :
That’s because you are calling getInstance() twice.
config.getInstance().setURISource(reader.get("uriSource"));
Instead, you can directly do this:
config.setURISource(reader.get("uriSource"));
Also, variables mustn’t be final if you want to set them later.