【发布时间】:2014-08-24 11:43:16
【问题描述】:
我之前在简单的问题上实现了抽象工厂模式并且它很有效。所以我试图用同样的东西来解决这个问题,但我很困惑。我编写了底层类,但对如何将它们组合成一个程序感到困惑。我应该怎么做?应该怎么做?
我正在使用 Java 编写代码来计算税收。我有基类TaxPayer。纳税人可以有多个incomeSource。 TaxPayer 或 IncomeSource 可以有多种类型。可以有许多不同收入来源的收入标题作为其属性,将存储在数据库中。 taxableIncome的不同纳税人类型和金额的税率会有所不同。
基类纳税人定义为
public abstract class TaxPayer {
private List<IncomeSource> incomeSource;
double taxRate;
Address address;
other attributes here;
public Double getTaxRate(){
return 0.25; //default tax rate
}
}
public abstract class IncomeSource {
private String incomeSourceName;
private Double incomeHeading1, incomeHeading2, incomeHeading3;
private Double totalIncome = incomeHeading1 + incomeHeading2 + incomeHeading3;
}
可以有更多级别的IncomeSource 继承与不同的收入标题。同样的纳税人类型可以建模成如下继承结构
Base Class: Taxpayer
* IndividualPerson
* Male, Female, OldAge
* Business
* Bank, ITIndustry, HydroElectricIndustry
* TaxFree
* SocialOrganization, ReligiousOrganization, PoliticalParty etc.
TaxPayer 的子类一般会修改taxRate 以应用于taxableIncome,有时还会通过一些逻辑更改taxableIncome。举个例子:
abstract class IndividualPerson extends TaxPayer{
if (incomeSource.taxableIncome > 250000) taxRate = ratex;
if (incomeSource.taxableIncome > 500000) taxRate = ratey;
@override
public getTaxRate() {
return taxRate;
}
}
class Female extends IndividualPerson {
if (incomeSource.getNumberOfIncomeSource() > 1) taxRate = taxRate + rate1;
else taxRate = taxRate - rate2
if (address.isRural() = true) taxRate = taxRate - rate3;
if (attributeX = true) taxRate = taxRate + rate4;
if ("Some other attribute" = true) taxableIncome = taxableIncome - someAmount;
}
我们必须检查Taxpayer 和IncomeSource 的其他属性以确定taxRate。大多数情况下,taxRate 对于不同的逻辑是不同的,但有时,taxableIncome 可以打折。
我正在尝试根据 TaxPayer 类型和 taxableIncome 返还税率。我很困惑如何将底层类组合在一起。
【问题讨论】:
-
为什么会有如此复杂的层次结构——例如,
Male和FemaleTaxpayer类如何添加任何东西?我认为你需要重新考虑你的类——你需要考虑什么时候可以有一个参数。 Effective Java(large pdf) 第 16 条:优先组合而不是继承。例如,在您的Male/Female案例中使用enum。 -
男性和女性的税率不同。所以我认为拥有这些会更好。怎么改成组合而不是继承?
-
这可以通过添加税率变量来解决。如果您尝试将每个变量描述为层次结构,您最终会陷入混乱。应该使用层次结构来改变行为而不是状态。
-
那么,将 getTaxRate() 替换为 Double taxRate 应该是正确的做法吗?
-
我想我在
Male、Female和其他继承TaxPayer类的类中会有更复杂的逻辑。我想要带有继承的多态性。可以用enum实现吗?
标签: java oop inheritance design-patterns