Reputation: 273
I am trying to create a class that has a singleton property using a static factory method..
package ishan.Beans;
public class ControlManager {
private static ControlManager controlManager=null;
private double id;
private ControlManager()
{
this.id=Math.random();
}
public static ControlManager getControlManager()
{
if(null==controlManager)
return new ControlManager();
return controlManager;
}
public double getId() {
return id;
}
}
package ishan.Beans;
public class Usage {
public static void main(String a[])
{
ControlManager cManager=ControlManager.getControlManager();
ControlManager c=ControlManager.getControlManager();
System.out.println(c);
System.out.println(cManager);
}
}
Every time I run this code, I get different instances of ControlManager in c and cManager. I am unable to figure out the problem or what is it that I am doing wrong.
Upvotes: 3
Views: 101
Reputation: 724
Your code should be change as:
public static ControlManager getControlManager() {
if(controlManager == null)controlManager = new ControlManager();
return controlManager;
}
Good Luck !!!
Upvotes: 0
Reputation: 8386
Change your getControlManager()
:
From
return new ControlManager();
to
controlManager = new ControlManager();
This is, what it should look like in the end:
public static ControlManager getControlManager() {
if(controlManager == null) {
controlManager = new ControlManager();
}
return controlManager;
}
In addition something opinion based, but backed up by conventions imo:
When writing conditional statements (if
) the order of your conditions should stick to the way of naturally speaking the statement. Example:
if (null == contorlManager)
if (controlManager == null)
The reason or goal behind this is, to keep your code readable. No one asks: "Is green the traffic light?".
For further information on this, see Yoda Conditions
Upvotes: 0
Reputation: 17707
You are not saving away the new instance you create... your code is:
public static ControlManager getControlManager() { if(null==controlManager) return new ControlManager();
but should be:
public static ControlManager getControlManager() {
if(controlManager == null) {
controlManager = new ControlManager();
return controlManager;
}
Upvotes: 1