Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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");
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top