SystemVerilog OOP Mastery · All levels
Factory Pattern: Polymorphism with Type and Instance Overrides: Code Examples
Code Examples for Factory Pattern: Polymorphism with Type and Instance Overrides.
Code examples
Global type override for all sequence-item creations
systemverilog
class base_item extends uvm_sequence_item;\n `uvm_object_utils(base_item)\n rand bit [31:0] addr;\n function new(string name = "base_item"); super.new(name); endfunction\nendclass\n\nclass ecc_item extends base_item;\n `uvm_object_utils(ecc_item)\n rand bit [6:0] ecc;\n function new(string name = "ecc_item"); super.new(name); endfunction\nendclass\n\nclass smoke_test extends uvm_test;\n `uvm_component_utils(smoke_test)\n function void build_phase(uvm_phase phase);\n super.build_phase(phase);\n base_item::type_id::set_type_override(ecc_item::get_type());\n endfunction\nendclassEvery `base_item::type_id::create` now returns `ecc_item`, preserving polymorphism while changing behavior globally for this test.
Instance override for one hierarchy path
systemverilog
class perf_test extends uvm_test;\n `uvm_component_utils(perf_test)\n function void build_phase(uvm_phase phase);\n super.build_phase(phase);\n my_driver::type_id::set_inst_override(\n latency_driver::get_type(),\n "uvm_test_top.env.tx_agent.drv"\n );\n endfunction\nendclassOnly `tx_agent.drv` is replaced; other `my_driver` instances are untouched. This is ideal for A/B experiments inside the same environment topology.
Factory creation keeps base-handle API stable
systemverilog
class my_sequence extends uvm_sequence #(base_item);\n `uvm_object_utils(my_sequence)\n virtual task body();\n base_item req;\n req = base_item::type_id::create("req");\n start_item(req);\n assert(req.randomize());\n finish_item(req);\n endtask\nendclassSequence code never hardcodes a derived class, so future overrides keep working without refactoring transactional flow code.