如何使用设计模式实现多级继承

时间:2014-08-24 11:43:16

标签: java oop inheritance design-patterns

我以前在简单的问题上实现了抽象工厂模式,并且它有效。所以我试着用同样的东西来解决这个问题,但我很困惑。我编写了底层课程但却混淆了如何将它们组合到一个程序中。我该怎么做以及如何做?

我正在使用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的{​​{1}},有时会使用某些逻辑更改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可以打折。

我正在根据TaxPayer类型和taxableIncome尝试退税率。我很困惑如何将底层课程结合在一起。

1 个答案:

答案 0 :(得分:1)

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下联合所有最低级别的班级。

做上面这样的事情。希望它能给你一个更清晰的想法。