簡體   English   中英

如何使用設計模式實現多級繼承

[英]How to implement multilevel inheritance using design pattern

我以前在一些簡單的問題上實現了“抽象工廠模式”,但它確實有效。 所以我試圖用同樣的東西解決這個問題,但是我很困惑。 我寫了底層類,但對如何將它們組合成一個程序感到困惑。 我應該怎么做,應該怎么做?

我正在使用Java編寫代碼來計算稅金。 我有基類TaxPayer 納稅人可以擁有多個incomeSource 可以有許多類型的TaxPayerIncomeSource 不同收入來源可能有許多收入標題作為其屬性,這些收入標題將存儲在數據庫中。 該稅率將針對不同納稅人的種類和數量不同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;
}

我們必須檢查TaxpayerIncomeSource其他屬性,以確定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等作為ENUMSbusiness類別下,以實現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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM