문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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");
        }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top