[英]Overridden method in derived class
I have an abstract class with an abstract method and this class is inherited by over 100 other classes where we override this virtual method.我有一个带有抽象方法的抽象类,这个类被 100 多个其他类继承,我们在这些类中重写了这个虚拟方法。
Now there is a slight change in business requirement and we need to do a check before calling the overridden method.现在业务需求略有变化,我们需要在调用覆盖的方法之前进行检查。 I know I can put a check in each of the 100 class but that doesn't seems to be an elegant way where change is required in all derived classes.
我知道我可以检查 100 个类中的每一个,但这似乎不是一种优雅的方式,在所有派生类中都需要更改。
Is there a better approach to handle this change?有没有更好的方法来处理这种变化?
public abstract class BaseFunction
{
public abstract Result FunctionCall();
}
public class Function1 : BaseFuction
{
public override Result FunctionCall()
{
//business logic
}
}
You can add a wrapper method to your base class like FunctionCallWithCheck
, that will perform the check, and then call the original abstract method FunctionCall
.您可以将包装方法添加到您的基类中,例如
FunctionCallWithCheck
,它将执行检查,然后调用原始抽象方法FunctionCall
。
In order to customize the check, I put it in a virtual method with a default implementation that you can override (if needed) in derived classes.为了自定义检查,我将它放在具有默认实现的虚拟方法中,您可以在派生类中覆盖(如果需要)。
Note: You will have to replace all you calls to FunctionCall
, with FunctionCallWithCheck
(in the code that uses all these classes).注意:您必须将所有对
FunctionCall
的调用替换为FunctionCallWithCheck
(在使用所有这些类的代码中)。
Of course this is a good approach only if there aren't too many places where you call FunctionCall
(you didn't supply info about that).当然,仅当您调用
FunctionCall
的地方不多(您没有提供有关该信息的信息)时,这才是一个好方法。
public abstract class BaseFunction
{
// Default check. You can override it in derived classes if needed.
public virtual bool Check()
{
return true; // put your conditions here
}
public int FunctionCallWithCheck()
{
if (Check())
{
return FunctionCall();
}
return -1;
}
protected abstract int FunctionCall();
};
public class Function1 : BaseFunction
{
protected override int FunctionCall()
{
//business logic
return 1;
}
};
I replaced the return type to int
since you did not supply the defintion for Result
.我将返回类型替换为
int
因为您没有提供Result
的定义。 I assume it has some default value in case the conditions for calling FunctionCall
were not met (instead of the -1
value that I used for that).我假设它有一些默认值,以防不满足调用
FunctionCall
的条件(而不是我使用的-1
值)。
Update:更新:
As @KlausGütter commented, you can make FunctionCall
into a protected
method (rather than public
), in order to get a compiler error if you accidently called it instead of FunctionCallWithCheck
.正如@KlausGütter 评论的那样,您可以将
FunctionCall
设置为protected
的方法(而不是public
),以便在您不小心调用它而不是FunctionCallWithCheck
时获得编译器错误。 I updated my code above.我在上面更新了我的代码。
If you'd rather not change it because of the many derived classes, you can also keep it public
(but you'll loose the compiler's protection).如果由于派生类很多而不想更改它,您也可以将其
public
(但您将失去编译器的保护)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.