在Java中,数据类的替代选择是什么?

huangapple go评论65阅读模式
英文:

What are the alternatives of a data class in java?

问题

我正在重构汽车租赁系统的代码。租赁类记录了每次租赁的持续时间、里程和汽车类型。它有一个方法根据这些属性计算最终费用。

有3种(可能更多)不同日租价格的汽车类型。在ComputeCost方法中逐个检查每种汽车类型显然不是最佳解决方案。然而,多态似乎也不是合适的解决方案,因为不同的汽车类型没有实现额外的功能;它们只是有不同的费率。将ComputeCost方法移动到这些子类中的任何一个也不太合适,因为该方法更多地依赖于租赁属性,如里程和持续时间,而不仅仅是汽车类型。

英文:

I am refactoring a car rental system code. The rental class keeps record of each rental duration, mileage, and car type. It has a method to compute final cost based on these attributes.

There are 3 (possibly more) car types with different daily prices. Checking each car type in the ComputeCost method is obviously not the best solution. However, polymorphism doesn't seem the appropriate solution either, since different car types don't implement extra functionality; they just have different rates. Moving the ComputeCost method to each of these subclasses doesn't also seem appropriate, since the method depends more on rental attributes like mileage and duration than on car type.

答案1

得分: 1

听起来你真的想要一个Rate类。

而且那个Rate类有一个computeCost(Rental)方法,用于计算使用给定费率的特定租赁的费用。

现在,如果不同费率之间唯一的区别是数值,那么Rate类本身可以是一个相当基本的类,只需有几个字段。

英文:

It sounds like you really want a Rate class.

And that Rate class has a computeCost(Rental) method that computes the cost of a given rental with a given rate.

Now if all that's different between the different Rates are numerical values, then the Rate class can itself be a pretty basic class with a couple of fields.

huangapple
  • 本文由 发表于 2020年10月9日 18:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64278704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定