Reputation: 73
I am unable to create an object using singleton design pattern, here is what I did:
class Test {
public static Test objTest = null;
public static int count = 0;
public static Test CreateObject() {
if (objTest != null)
objTest = new Test();
return objTest;
}
private Test() {
Test.count++;
}
}
Have I created zeroton pattern ?
Upvotes: 1
Views: 93
Reputation: 2760
Check your if condition inside createObject
method once. it should be if(objTest == null)
.
Upvotes: 5
Reputation: 11
The objTest variable should also be private, you'll not want to reference to a null instance. Access to the instance should only be possible through your CreateObject() method.
Upvotes: 1
Reputation: 2147
Besides the fact, that your count would always be either '0' or '1' (ignoring potential multi-threading issues) - why do you have that parameter?
You are checking for objTest != null
instead of objTest == null
.
That's why you are always returning null
and never create a new instance.
Upvotes: 1