Sometimes it is required to have only one object of some classes like configuration classes. For this purpose we create singleton classes. Only one object is created for a singleton class and whenever we try to create a new object, same object is returned.
System verilog does not provide construct to create a singleton class. But we can create it with some manupulations
01.
// Filename : singleton.sv
02.
// Author : Puneet (er.punit@gmail.com)
03.
// Website : http://www.asicguru.com
04.
05.
class
singleton;
06.
int
len;
07.
08.
static
singleton objSingle;
09.
10.
local
function
new
(
int
len=0);
11.
this
.len = len;
12.
endfunction :
new
13.
14.
function
void
print_len ();
15.
$display(
"Len is = %d"
, len);
16.
endfunction : print_len
17.
18.
static
function
singleton create (
int
len=0);
19.
if
(objSingle == null)
begin
20.
$display(
"Object is null creating new object \n"
);
21.
objSingle =
new
(len);
22.
end
23.
24.
return
objSingle;
25.
endfunction : create
26.
27.
endclass
28.
29.
program main;
30.
31.
singleton objSingle1;
32.
singleton objSingle2;
33.
34.
initial
35.
begin
36.
objSingle1 = singleton::create ( );
37.
objSingle2 = singleton::create ( );
38.
39.
$display(
"Testing Singleton object \n"
);
40.
objSingle2.len = 10;
41.
objSingle1.print_len();
// Call print len function
42.
objSingle2.print_len();
// Call print len function
43.
44.
objSingle1.len = 99;
45.
objSingle1.print_len();
// Call print len function
46.
objSingle2.print_len();
// Call print len function
47.
end
48.
49.
endprogram: main
50.
51.
52.
53.
54.
//Output
55.
Object is null creating
new
object
56.
57.
Testing Singleton object
58.
59.
Len is = 10
60.
Len is = 10
61.
Len is = 99
62.
Len is = 99
63.
V C S S i m u l a t i o n R e p o r t