Reputation: 1588
I have this Object which will be used to store connection credentials:
public static class NewAgentObj
{
private String hostName;
private int port;
private String userName;
private String passwd;
public static NewAgentObj newInstance()
{
return new NewAgentObj();
}
public NewAgentObj()
{
}
/**
* An easier way to set a new value or optional arguments are provided when create a new instance. Can be used as alternative to set method
*
* @param hostName
* @return
*/
public NewAgentObj hostName(String hostName)
{
this.hostName = hostName;
return this;
}
/**
*
* @param port
* @return
*/
public NewAgentObj port(int port)
{
this.port = port;
return this;
}
/**
*
* @param userName
* @return
*/
public NewAgentObj userName(String userName)
{
this.userName = userName;
return this;
}
/**
*
* @param passwd
* @return
*/
public NewAgentObj passwd(String passwd)
{
this.passwd = passwd;
return this;
}
public String getHostName()
{
return hostName;
}
public int getPort()
{
return port;
}
public String getUserName()
{
return userName;
}
public String getPasswd()
{
return passwd;
}
}
I use this code to insert values:
NewAgentObj ob = NewAgentObj.newInstance().hostName(filed.getText());
But when I try to get the data into another Java class I use this code:
NewAgentObj ob = NewAgentObj.newInstance();
Label finalFieldAgentName = new Label(ob.getHostName());
I get null value. Can yuo tell me how I can get value from the Java Object?
Upvotes: 2
Views: 329
Reputation: 36449
The whole point of a Singleton is that it stores a static instance of your Object so it can be reused among multiple classes. Obviously if every time you call getInstance()
you make a new
Object, you are never able to hold data; it gets discarded almost immediately.
To make a singleton, hold a reference to an actual instance.
private static NewAgentObj instance; //your static, reusable instance
public static NewAgentObj newInstance(){
if (instance == null){
instance = new NewAgentObj(); //only create the Object if it doesn't exist
}
return instance;
}
For clarity's sake, I'd rename this method to getInstance()
to more accurately convey its purpose.
Keep in mind as well that you are able to pass Objects around as arguments to Constructors/methods, thus not needing the singleton pattern.
Upvotes: 4
Reputation: 3331
With this line
NewAgentObj ob = NewAgentObj.newInstance();
you only get new instance of NewAgentObject with all null values.
Because of that you get null.
Instead of that you have to use singleton pattern to ensure only one instance, which holds all values.
Upvotes: 0