+-
如何通过从继承转移到组合来简化Java代码
我编写了多级继承类的底层类,但混淆了如何将它们组合到单个程序中.有人建议我使用组合而不是继承,有人建议使用枚举来创建匿名子类而不是复杂的继承结构.我们如何使用组合来代替继承或使用枚举而不是我使用的继承?我该怎么做才能简化问题,应该怎么做?

我正在使用Java编写代码来计算税收.我有基类TaxPayer.纳税人可以有多个incomeSource. TaxPayer或IncomeSource可以有多种类型.每个收入来源可以有许多收入标题,用于计算taxableIncome.对于不同类型的taxPayer和taxableIncome,taxRate会有所不同.最终结果将taxRate应用于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 taxableIncome = 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;
}

我们必须检查纳税人和IncomeSource的属性以确定taxRate.有时,taxableIncome可以根据taxPayer类型和其他条件进行修改.

我很困惑如何将底层类组合在一起以制作可用的代码.有人建议我不要使用复杂的多级继承,而是使用组合或枚举以更低的复杂度实现所需的结果.这该怎么做?请给出足够详细的答案,供初学者理解.

最佳答案
这是更好的组成变化.
您可以这样做,从多继承或接口更改为组合

>继承:

Class A{ }
Class B extends Class A{ }
Class C extends Class B{ }

>界面:

Interface A{ }
Interface B implements Class A{ }
Class C implements Class B{ }

>成分:

class C{  
    A objA = new A();  
    B objB = new B();

    pubic void test(){  
        objA.doSomething();
    } 
    public void methodA(){ 
        objA.method();
    }
}
点击查看更多相关文章

转载注明原文:如何通过从继承转移到组合来简化Java代码 - 乐贴网