我不确定我是否正确理解模板方法模式。

这是我的简化基类实现:

public abstract class AlgorithmBase
{
    protected void AlgorithmMethod()
    {
        if(!OnSimulationStart())
        {
            OnSimulationEnd(false);
            return;
        }

        if(!DoSomeStep())
        {
            OnSimulationEnd(false);
            return;
        }

        OnSimulationEnd(true);
    }

    protected abstract bool OnSimulationStart();
    protected abstract bool DoSomeStep();
    protected abstract void OnSimulationEnd(bool result);
}
.

据我所知,基类知道算法流程并管理它。 问题是,在真正的项目中,我有许多抽象方法,如果我可以以某种方式阻止直接在派生类中调用它们会很好。当多个类管理算法流量时,它是不可读的。

有帮助吗?

解决方案

基于显式实现接口的技巧可用于防止基本算法实现所需的方法的意外调用。但是,这是一种如此安全措施,可以破碎,但是开发商会知道他会做什么的机会很高。

AlgorithmMethod所需的接口声明方法:

public interface IAlgorithmMethodImpl
{
    bool OnSimulationStart();
    bool DoSomeStep();
    void OnSimulationEnd(bool result);
}
.

基础抽象类,使用此接口,传递到其构造函数,调用所需的方法:

public abstract class AlgorithmBase
{
    protected AlgorithmBase(IAlgorithmMethodImpl impl)
    {
        Impl = impl;
    }

    // can be a property reasonable cases; however, a field 
    // fits well into our scenario
    private IAlgorithmMethodImpl Impl; 

    protected void AlgorithmMethod()
    {
        if(!Impl.OnSimulationStart())
        {
            Impl.OnSimulationEnd(false);
            return;
        }

        if(!DoSomeStep())
        {
            Impl.OnSimulationEnd(false);
            return;
        }

        Impl.OnSimulationEnd(true);
    }

    // no abstract method declarations here — they are provided by 'Impl'
}
. 然后

然后从世乡科odicetagcode继承的特定算法类使用显式接口实现来封装必要方法的实现(如在基础上声明的抽象方法)类,同时阻止它们被意外调用:

public class MySuperAlgorithm : AlgorithmBase, IAlgorithmMethodImpl
{
    public MySuperAlgorithm()
        // pass a reference to this instance as the class 
        // that implements the required methods
        : base(this) 
    {
    }

    // explicit implementation of IAlgorithmMethodImpl
    bool IAlgorithmMethodImpl.OnSimulationStart() { ... implementation ... }
    bool IAlgorithmMethodImpl.DoSomeStep() { ... implementation ... }
    void IAlgorithmMethodImpl.OnSimulationEnd(bool result) { ... implementation ... }
}
.

此批准的优势 - 除了防止实施方法的意外调用 - 是您可以选择是否封装在后代中的实现,或者将其分解为单独的类。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top