I'm currently in a situation where I have multiple derived class types(just one is shown in the example below) that need to apply some logic before and/or after calling a method implemented in a common base class. I have two scenarios below and was wondering what would be a downside and upside for each approach in this use case scenario? The client code will be calling the relevant classes as defined in the main stub. The template method design pattern that is presumably being followed correctly in scenario b seems to be more popular based on research, but from first glance the code for approach a looks to be more minimal.
Thank you.
Scenario A:
using System.IO;
using System;
interface IContract
{
void Foo();
};
abstract class Base : IContract
{
protected void FooImpl()
{
Console.WriteLine("base work");
}
public abstract void Foo();
};
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("pre work derived");
FooImpl();
Console.WriteLine("post work derived");
}
}
class Program
{
static void Main()
{
IContract contract = new Derived();
contract.Foo();
}
}
Scenario B:
using System.IO;
using System;
interface IContract
{
void Foo();
};
abstract class Base : IContract
{
protected abstract void PreFooHook();
protected abstract void PostFooHook();
public void Foo()
{
PreFooHook();
Console.WriteLine("base work");
PostFooHook();
}
};
class Derived : Base
{
protected override void PreFooHook()
{
Console.WriteLine("pre work derived");
}
protected override void PostFooHook()
{
Console.WriteLine("post work derived");
}
}
class Program
{
static void Main()
{
IContract contract = new Derived();
contract.Foo();
}
}
Desired Output:
pre work derived
base work
post work derived