Jump to content

Non-virtual interface pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by DragonGod2718 (talk | contribs) at 02:25, 19 September 2021 (Rewrote the C# Example of the pattern to something much more readily accessible.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

The non-virtual interface pattern (NVI) controls how methods in a base class are overridden. Such methods may be called by clients and overridable methods with core functionality.[1] It is a pattern that is strongly related to the template method pattern. The NVI pattern recognizes the benefits of a non-abstract method invoking the subordinate abstract methods. This level of indirection allows for pre and post operations relative to the abstract operations both immediately and with future unforeseen changes. The NVI pattern can be deployed with very little software production and runtime cost. Many commercial software frameworks employ the NVI pattern.

Benefits and detriments

A design that adheres to this pattern results in a separation of a class interface into two distinct interfaces:

  1. Client interface: This is the public non-virtual interface
  2. Subclass interface: This is the private interface, which can have any combination virtual and non-virtual methods.

With such a structure, the fragile base class interface problem is mitigated. The only detriment is that the code is enlarged a little.[2]

C# Example

public abstract class Saveable
{
    public void Save()
    {
        CoreSave();
    }
 
    protected abstract void CoreSave();
}
 
 
public class Customer : Saveable
{
    public string Name { get; set; }
    public decimal Credit { get; set; }
 
    protected override void CoreSave()
    {
        Console.WriteLine("Saved customer {0} with credit limit {1}", Name, Credit);
    }
}

[3]

See also

References

  1. ^ Carr, Richard (2011-09-03). "Non-Virtual Interface Design Pattern". BlackWasp. Archived from the original on 2011-09-03. Retrieved 2012-09-12. The non-virtual interface pattern is a design pattern that controls how methods in a base class are overridden. Base classes include public, non-virtual members that may be called by clients and a set of overridable methods containing core functionality.
  2. ^ Tambe, Sumant (2007-04-11). "Non-Virtual Interface (NVI) idiom and the design intent". C++ truths. Archived from the original on 2007-04-11. Retrieved 2012-09-12.
  3. ^ "Non-Virtual Interface Design Pattern". www.blackwasp.co.uk. Retrieved 2021-09-19.