Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template method pattern without inheritance

How can a variant of the Template Method pattern be implemented whereby the concrete class does not inherit from the base class, but the overall feature of the pattern is maintained. The reason it cannot inherit is that it's forced to inherit from another class and multiple-inheritance is unavailable.

For example, suppose the following Tempate Method pattern:

public abstract class BaseClass {
    public void Alpha() {
        Beta();
    }

    public abstract void Beta();

    public void Gamma() {
        Delta();
    }

    public abstract void Delta();

}

public ConcreteClass : BaseClass {
    public override void Beta() {
        Gamma();
    }

    public override void Delta() {
        Console.WriteLine("Delta");
    }
}

...
var object = new ConcreteClass();
object.Alpha(); // will outout "Delta"

How can I achieve the same result without ConcreteClass inheriting BaseClass?

like image 288
Herman Schoenfeld Avatar asked Jul 17 '13 06:07

Herman Schoenfeld


1 Answers

Your base class could depend on an interface (or other type) that's injected via the constructor. Your template method(s) could then use the methods on this interface/type to achieve the pattern's desired outcome:

public class BaseClass 
{
    IDependent _dependent;

    public BaseClass(IDependent dependent)
    {
         _dependent = dependent;
    }

    public void Alpha() {
        _depdendent.Beta();
    }

    public void Gamma() {
        _depdendent.Delta();
    }

}

Effectively using composition rather than inheritance.

like image 82
David Osborne Avatar answered Oct 21 '22 22:10

David Osborne