Non-virtual interface pattern: Difference between revisions

Content deleted Content added
m WP:CHECKWIKI errors fixed using AWB (8967)
C# example: add image
 
(10 intermediate revisions by 7 users not shown)
Line 4:
| last1 = Carr
| first1 = Richard
| authorlink1 = https://profiles.google.com/113882985360066691734| date = 2011-09-03
| date = 2011-09-03
| work =
| publisher = BlackWasp
| archiveurl = http://www.blackwasp.co.uk/NVI.aspx
Line 18 ⟶ 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 protectedprivate 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 ⟶ 23:
| last1 = Tambe
| first1 = Sumant
| authorlink1 = https://plus.google.com/117220997561739301261| date = 2007-04-11
| date = 2007-04-11
| work =
| publisher = C++ truths
| archiveurl = http://cpptruths.blogspot.co.at/2007/04/non-virtual-interface-nvi-idiom-and.html
Line 34 ⟶ 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 ==