Non-virtual interface pattern: Difference between revisions

Content deleted Content added
"Virtual functions should be private". According to external link and Herb Sutter book (More Exceptional C++, problem 18).
C# example: add image
 
(8 intermediate revisions by 5 users not shown)
Line 5:
| first1 = Richard
| authorlink1 = | date = 2011-09-03
| work =
| publisher = BlackWasp
| archiveurl = http://www.blackwasp.co.uk/NVI.aspx
Line 17 ⟶ 16:
A design that adheres to this pattern results in a separation of a class interface into two distinct interfaces:
# Client interface: This is the public non-virtual interface
# Subclass interface: This is the private (interface, which can have any combination virtual and non-)virtual interfacemethods.
 
With such a structure, the [[fragile base class]] interface problem is mitigated. The only detriment is that the code is enlarged a little.<ref>{{cite web
Line 25 ⟶ 24:
| first1 = Sumant
| authorlink1 = | date = 2007-04-11
| work =
| publisher = C++ truths
| archiveurl = http://cpptruths.blogspot.co.at/2007/04/non-virtual-interface-nvi-idiom-and.html
Line 32 ⟶ 30:
| accessdate = 2012-09-12
}}</ref>
 
== C# example ==
[[File:Non-virtual interface pattern.svg]]
 
<syntaxhighlight lang="c#" line="1">
public abstract class Saveable
{
// The invariant processing for the method is defined in the non virtual interface.
// The behaviour so defined is inherited by all derived classes.
// For example, creating and committing a transaction.
public void Save()
{
Console.WriteLine("Creating transaction");
CoreSave();
Console.WriteLine("Committing transaction");
}
// The variant processing for the method is defined in the subclass interface.
// This behaviour can be customised as needed by subclasses.
// For example the specific implementation of saving data to the database.
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 {Name} with credit limit {Credit}");
}
}
</syntaxhighlight><ref>{{Cite web|title=Non-Virtual Interface Design Pattern|url=http://www.blackwasp.co.uk/nvi.aspx|access-date=2021-09-19|website=www.blackwasp.co.uk}}</ref><ref>{{Cite web|title=Non-Virtual Interface Design Pattern (Page 2 of 2)|url=http://www.blackwasp.co.uk/nvi_2.aspx|access-date=2021-09-19|website=www.blackwasp.co.uk}}</ref>
 
== See also ==
* [[Template method pattern]]
 
== References ==