模板方法模式-防止在派生类中直接调用方法



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

这是我的简化基类实现:

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'
}

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

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 ... }
}

这种方法的优点除了可以防止意外调用实现方法之外,还可以选择是将实现封装在子代中,还是将其分解为一个单独的类。

最新更新