Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO Pattern: Shared work between abstract base class and subclasses

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:

  • Is there an option which is clearly preferred?
  • Is this a well-known pattern that has a name (so that I can do more research)?
  • Are there well-established naming conventions for situations like this (i.e. for the _Do... thing)?
like image 464
Heinzi Avatar asked Dec 22 '22 05:12

Heinzi


1 Answers

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.
like image 196
Anton Gogolev Avatar answered Jan 25 '23 23:01

Anton Gogolev