繁体   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