Hi,
As per the standard definition of singleton class, only one object is created for a singleton class and whenever we try to create a new object, same object is returned.
I have tried to develop a small piece of code of the same and as follows.
class singleton;
int value;
static singleton obj_singleton;
function new();
endfunction
function void display ();
$display ("%t %M: value=%0d ",$time, value );
endfunction
static function singleton create ();
if (obj_singleton == null)begin
obj_singleton = new();
$display("Creating object ");
return obj_singleton;
end
else $display("Already object exists");
endfunction
endclass
program ex;
singleton o_singleton1;
singleton o_singleton2;
initial begin
o_singleton1 = singleton::create();
o_singleton2 = singleton::create();
$display ("%t %M: Testing of singleton class",$time );
o_singleton1.value = 10;
o_singleton1.display();
o_singleton2.display();
o_singleton2.value = 20;
o_singleton1.display();
o_singleton2.display();
end
endprogram
When I try to run the above code, simulator gives error Null pointer dereference in Line o_singleton1.value = 10; .
I know that I have not constructed the class inside initial begin…end in program…endprogram. So it’s illegal to use handle to access the property/method unless property/method.
I can resolve this issue by using property value as static but that is not my intention.
I want to have only object and whenever I change the value of variable “value” in anyone of the object (o_singleton1 and o_singleton2) but actually both are same, both o_singleton1 and o_singleton2 should have the same value according to singleton class definition.
How do I realize this in the above piece of code? Can anyone help me to understand it in better way.
Thank you.
Regards,
Ashwath