我之前曾在简单问题上实现过抽象工厂模式,并且它有效。所以我尝试使用同样的东西来解决这个问题,但我很困惑。我编写了底层类,但对如何将它们组合到一个程序中感到困惑。我应该做什么以及如何做?
我正在使用Java编写代码来计算税金。我有基类 TaxPayer
。纳税人可以有多个收入来源。 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
的子类通常会修改要应用于 taxableIncome
的 taxRate
,有时还会通过某些逻辑更改 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
可以打折扣。
我正在尝试根据纳税人类型和应税收入返回税率。我很困惑如何将底层类(class)组合在一起。
最佳答案
创建Taxpayer
作为父接口(interface)
,层次结构中下面的三个接口(interface)将实现它。此taxpayer
接口(interface)将有一个getTaxRate()
方法,需要由所有子类实现。
您可以将 business
类作为扩展父 taxpayer
接口(interface)的另一个接口(interface),并使 bank,Hydroelectricity
类扩展 business
接口(interface)。
每个银行、水力发电
等都会有一个具有所需税率的最终 float
。
假设 A 是一个在银行有业务的人员类别,所以在这种情况下
A implements Bank
这将提供 A 银行特定的税率。
但更好的选择是将银行、水电
等作为business
类下的ENUMS
,该类应实现Taxpayer
接口(interface)。
更好的方法
public enum Business {
BANK(10.1), ITINDUSTRY(8.1), HYDROELECTRICITY(1.3);
private float value;
private Business(int value) {
this.value = value;
public float getTaxRate(){
return this.value;
}
};
class A implements TaxPayer{
public String occupation = "BANK";
//implemented from parent taxpayer
public float getTaxRate(){
return Business.BANK.getTaxRate();
}
}
如果纳税人下的隔离并不重要,那么您可以将所有最低级别的类别归入一个 ENUM 下。
做类似上面的事情。希望它能给您一个更清晰的想法。
关于java - 如何使用设计模式实现多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25471340/