我们可以用C#中的对象替换if语句吗
下面是一个方法:
private RiskFactor calculateMotoristRiskFactor()
{
if (motorist.PointsOnLicense > 3
|| motorist.Age < 25)
return RiskFactor.HighRisk;
if (motorist.PointsOnLicense > 0)
return RiskFactor.ModerateRisk;
return RiskFactor.LowRisk;
}
我不需要那些 if 语句。
我可以使用策略模式来解决这个问题吗? 如果是,那么我也不希望不同多态类中的每个方法都应该有一个 If 语句。
RiskFactor 是一个枚举 有
什么更好的方法可以使其更加面向对象而不是过程化?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,你可以有一个
List, RiskFactor>
:那么:
这至少可以轻松添加额外的检查,并且它只是按顺序运行它们。这有点繁琐 - 例如,我可能会创建一个自定义
Filter
类型而不是Tuple
- 但它应该可以工作......Well, you could have a
List<Tuple<Func<Motorist, bool>, RiskFactor>
:Then:
That at least makes it easy to add extra checks, and it just runs down them in order. It's a little bit fiddly - I might create a custom
Filter
type rather than theTuple
for example - but it should work...我认为策略模式不应该是这里的答案 - 通常,如果您正在处理的特定类型的驾驶者影响其行为,您通常会使用策略。
在您的情况下,您只有基于驾车者属性的标准域逻辑。我认为有条件的处理是非常恰当的。
I don't think the strategy pattern should be the answer here - typically you would use a strategy if the particular type of motorist you are dealing with affects the behavior.
In your case you just have standard domain logic based on the properties of a motorist. I think the conditional handling is very appropriate.
完全取消
RiskFactor
函数。不要使用该函数的代码,而是将需要其返回值的逻辑封装到以不同方式执行任务的单独类中。例如,您可以定义一个抽象类
Policy
,它由LowRiskPolicy
、ModerateRiskPolicy
和HighRiskPolicy
继承。这些只是返回根据适当的策略计算的值,并且使用代码不知道或关心它们是什么类型的策略。所有特定于策略的逻辑都包含在策略中。Do away with the
RiskFactor
function entirely. Instead of the consuming code for that function, encapsulate the logic which requires its return value into seperate classes which perform the task differently.For example, you could define an abstract class
Policy
which is inherited byLowRiskPolicy
,ModerateRiskPolicy
andHighRiskPolicy
. These simply return values calculated according to the appropriate policy and the consuming code doesn't know or care what sort of policy they are. All the policy-specific logic is wrapped up in the policy.我不认为你需要更加面向对象只是为了更加面向对象。
如果它仅位于您计算风险的代码中,并且我假设还有根据年龄和许可点计算的其他数据数量,我会保留您的代码不变。
除了可能将 Motorist 作为参数传递给 RiscCalculator 类的方法之外。
以防万一这里有类似的例子 用多态性替换条件
I do not think you need to be more object oriented only just to be more object oriented.
If it's only place in code where you are calculating risk and I assume there are number of other data calculated based on age and points of license I would leave your code as it is.
Except probably passing Motorist as parameter to the method of RiscCalculator class.
Just in case similar example here Replace Conditional with Polymorphism
您将拥有更多代码,但它允许您将其分解出来。您可以为每种类型的风险因素创建一个策略类并将它们收集在一起。像这样的东西:
You are going to have a lot more code, but it will allow you to factor it out. You could create a policy class for each type of risk factor and collect them together. Something like this: