SystemVerilog​概念浅析之singleton class

SystemVerilog中Singleton class是指只有一个对象(object)的类。这个对象只创建一次,为所需的全局变量提供一个namespaces。

Singleton class定义全局的行为,例如printing。

Singleton class 在compile-time创建一个对象,然后在run-time操作其中的成员,不需要用户在仿真时在建立一个新的实例。

program top;
class singleton;
   int unsigned var1;

  //  Need to declare it as static, as  it is accessed by static method 'create'
  static  singleton single;

  //  Declared as 'protected', so  user can't directly create instance of this class
  protected functionnew();
  endfunction:new

  static functionsingleton  create();
     if (single ==null) begin
       $display("Object  single is null, so creating new object");
       single =new();
     end
     return single;
  endfunction:create
endclass:singleton
singleton s1,  s2;
initial begin
     s1 = singleton ::create();
     $display (" 1  : s1.var1 = %0d",  s1.var1);
     s1.var1 =10;
     $display (" 2  : s1.var1 = %0d",  s1.var1);

     s2 = singleton ::create();
     $display (" 3  : s2.var1 = %0d",  s2.var1);

     s2.var1 =20;
     $display (" 4  : s2.var1 = %0d",  s2.var1);
     $display (" 5  : s1.var1 = %0d",  s1.var1);
  end
endprogram

Output:    

//   1 : s1.var1 = 0
//   2 : s1.var1 = 10
//   3 : s2.var1 = 10
//   4 : s2.var1 = 20
//   5 : s1.var1 = 20

A singleton object is a globally accessiblestatic object providing customizable service methods.

Synopsys UVM1.2 Workshop

在下面的例子中:

class service_class;
           protected static service_class me =get();
           static function service_class get();
                      if(me = null) me = new() ;
                       return me ;
            endfunction
extern virtual function void error (string msg) ;
endclass

error method需要用户自行定义所需要的行为。

在UVM的workshop中使用了一个名称为proxy\_class的singleton class很好地诠释了其在factory机制的应用。

class proxy_class#(type T =base) ;
           type proxy_class#(T)  this_type ;  //just for coding convenience
           protected function new();
endfunction

static function this_type get();
           if(me== null) me = new() ;
           return me;
endfunction
static function T create();
           create=new() ;
function
endcase
class driver xtends base;
           typedef proxy_class(driver) proxy ;
endclass

class monitor xtends base;
           typedef proxy_class(monitor) proxy ;
endclass
class environment ;
           driver drv ;
           monitor mon;
           function new;
           drv = driver::proxy::create() ;
           mon = monitor::proxy::create() ;
endfunction
endclass

这个proxy class提供了一个创建不同的singleton bject的机制。

为了使proxy class更有意义,我们需要一个virtual base classfactory机制。proxy class根据不同的factory注册和base class生成特定的proxy object。

本文转载自公众号:芯片数字实验室
原文链接:
https://mp.weixin.qq.com/s/cjb6ZDa0uWkj8ts0VECcog
未经作者同意,请勿转载!

推荐阅读
SystemVerilog概念浅析之Covergroup

  • SystemVerilog概念浅析之virtual interface
  • SystemVerilog概念浅析之virtual class

想了解更多内容,欢迎关注芯片数字实验室专栏

发表评论

邮箱地址不会被公开。 必填项已用*标注