The Non-Virtual Interface (NVI) pattern controls how methods in a base class are overridden. Base classes use public, non-virtual functions that can be called by clients. Overridable methods are defined as protected, virtual members.
Problem
When creating an abstract base class, there is a tendency to make public methods virtual or abstract, allowing them to be overridden by subclasses.
When a base class method is overridden by a subclass, the subclass’s implementation may optionally call the base class method. However, this is not mandatory, and it is not easily enforced, so it is possible that key functionality implemented in the base class is not used in a subclass. This makes these classes harder to use correctly. Wouldn’t it be better if there was a way to enforce the use of key functionality in the base class?
Solution
The NVI pattern separates the core functionality of the base class from the public interface of the base class.
- Public methods of the base class are neither
virtualnorabstract, and cannot be overridden. Functionality that must be maintained in subclasses is contained in public members of the base class. - Public methods call
protected,virtualmembers in the base class. These functions contain core functionality that may be overridden by subclasses, or they may be pure abstract functions that must be implemented by the derived class.
This pattern results in two distinct interfaces:
- The public interface used by clients
- The private interface, which is used, extended, and/or implemented by subclasses.
While this pattern is usually used with class interfaces, the same ideas apply to library and framework interfaces.
Consequences
- This pattern mitigates the Fragile Base Class interface problem.
- This pattern requires minimal overhead to implement, but represents a reorganization of the base class’s functionality.
Known Uses
- The NVI pattern is one way to implement the Template Method pattern.
Related Patterns
- The NVI pattern is one way to implement the Template Method pattern.
References
- Non-virtual interface pattern – Wikipedia
- Template Method pattern
- Design Patterns VS Design Principles: Template Method – Fluent C++ – mentions the NVI pattern
« Back to Glossary Index
