[英]How to implement multilevel inheritance using design pattern
我以前在一些簡單的問題上實現了“抽象工廠模式”,但它確實有效。 所以我試圖用同樣的東西解決這個問題,但是我很困惑。 我寫了底層類,但對如何將它們組合成一個程序感到困惑。 我應該怎么做,應該怎么做?
我正在使用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退稅率。 我很困惑如何將底層類組合在一起。
創建Taxpayer
作為parent interface
,層次結構下面的三個將實現它。 此taxpayer
接口將具有getTaxRate()
方法,該方法需要由所有子類實現。
您可以將business
類作為擴展父taxpayer
接口的另一個接口,並使bank,hydroelectricity
類擴展business
接口。
每家bank,hydroelectricity
等都有final float
並具有所需的稅率。
假設A是在銀行有業務的人類,那么在這種情況下
A implements Bank
這將提供特定於A銀行的稅率。
但是更好的選擇是將bank,hydroelectricity
等作為ENUMS
在business
類別下,以實現Taxpayer
接口。
更好的方法
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中。
做上面的事情。 希望它能給您一個更清晰的主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.