I have an abstract base class T
, from which classes A
and B
inherit. I now have an operation (on T
) which requires a slightly different implementation in A
and B
, but most of the code is the same. Let me give you an example: There are two possibilities to implement something like a .Clone
method:
Public MustInherit Class T
Protected MustInherit Function _DoClone() As T
Public Function Clone() As T
Dim clone = Me._DoClone() ' do the subclass-specific stuff '
... ' do the shared stuff '
End Function
End Class
Public Class A
Inherits T
Protected Overrides Function _DoClone() As T
... ' do the subclass-specific stuff '
End Function
End Class
or
Public MustInherit Class T
Protected Sub _DoClone(clone As T)
... ' do the shared stuff '
End Function
Public MustInherit Function Clone() As T
End Class
Public Class A
Inherits T
Public Overrides Function Clone() As T
Dim clone = ... ' do the subclass-specific stuff '
Me._DoClone(clone)
End Function
End Class
(The example is in VB.NET, but the same question applies to C#, Java, etc.)
My questions:
_Do...
thing)?Looks like Template method pattern:
The template method is used to:
- let subclasses implement (through method overriding) behavior that can vary
- avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses
- control at what point(s) subclassing is allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With