Herman Schoenfeld
Herman Schoenfeld

Reputation: 8724

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?

Upvotes: 7

Views: 2297

Answers (2)

retler
retler

Reputation: 3

You can achieve this by providing a reference to the base class on method call:

public ConcreteClass {
    public void Beta(BaseClass baseClass) {
        baseClass.Gamma();
    }

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

Upvotes: 0

David Osborne
David Osborne

Reputation: 6791

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.

Upvotes: 5

Related Questions