UVM 源码中有使用到singleton object, 即单实例。 比如class:uvm_root, 有且只有一个实例。
OOP中的设计模式有很多,单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。
link:www.runoob.com/design-patt…
Singleton class
-
Used to define a "global" activity such as printing or class factory
-
No instance(object) of the singleton class exists
-
Contains only static properties and methods
class print; static int err_count=0, max_errors=10; static function void error (sting msg); $display("@%t:ERROR %s",$realtime,msg); if(err_count++ > max_errors) $finish; endfunction:error endclass:print if(expect != actual) print::error("Actual did not match expected");singleton class 内都是使用static修饰的变量和方法(静态变量,可全局访问,在编译时分配内存空间),无须创建实例,通过class_name:: 的形式即可调用。
Singleton object
-
A singleton object is a globally accessible static object which provides customized service methods
-
One and only one object in existence, created at compile-time
-
Globally accessible at run-time
-
Can have static and non-static members
-
class factory; static local factory me; static function factory get(); if(me==null) me=new(); return me; endfunction:get protected function new(); endfunction:new extern function void print(); endclass:factory factory f=factory::get();factory的实例me是静态的对象,并使用local修饰:只能被当前类的方法访问,不同对象间可以互相访问。扩展类不行。
*嵌套的类可以访问被嵌套类的local、protected、static等成员,有完全访问权。
构造函数new() 使用 protected修饰,表明能被当前类或者扩展类中的方法访问,不同对象间可以互相访问。
所以要新建一个实例,只能通过get()函数。而get()函数是静态方法,通过factory::get()调用。
同时一但factory::get()被执行一次,factory的实例me 就不在是null。
最后如果在其他地方调用factory::get(),只会指向静态变量me所指向的唯一实例。
以下为uvm_root 中的单例模式: