Template method pattern is commonly implemented with abstract classes.
interface Algorithm
{
void perform();
}
abstract class AlgorithmBase implements Algorithm
{
abstract void step1();
abstract void step2();
private void finalStep()
{
// common implementation
}
// Template method
public final void perform()
{
step1();
step2();
finalStep();
}
}
public class AlgorithmA extends AlgorithmBase
{
void step1()
{
// step 1 implementation
}
void step2()
{
// step 2 implementation
}
}
using
Algorithm a = new AlgorithmA();
a.perform();
But some languages (like Swift) don't support abstract classes. Implementation of template method pattern is done through interface delegation.
protocol Algorithm
{
func perform()
}
protocol AlgorithmSteps
{
func step1()
func step2()
}
class AlgorithmBase: Algorithm
{
var delegate: AlgorithmSteps
init(delegate: AlgorithmSteps)
{
self.delegate = delegate
}
private func finalStep()
{
// common implementation
}
// Template method
final func perform()
{
delegate.step1()
delegate.step2()
finalStep()
}
}
class AlgorithmA : AlgorithmSteps
{
func step1()
{
// step 1 implementation
}
func step2()
{
// step 2 implementation
}
}
let a : Algorithm = AlgorithmBase(delegate: AlgorithmA())
a.perform()
Obviously if language does not support abstract classes the only way to go is using interface delegation, but what if it does? Then template method pattern can be implemented either way.
Does second implementation has any advantages in terms of good OOP practices vs first one?