What is the best way to structure a group of variables that have a group of variables that have a group of variables and so on?

Alder Moreno :

I'm creating a Java program which calculates rates. The rate has a season which has its peaks and those peaks have their own hours and prices. I was thinking of doing nested classes, but there's got to be a better way that I'm just not thinking about it right?

Variables that I need to store:

Rate
    Summer
        peak
            hours
            price
        midpeak
            hours
            price
        off-peak
            hours
            price
    Non-summer
        peak
            hours
            price
        midpeak
            hours
            price
        off-peak
            hours
            price
SuryaVal :

Here is an approach:

class BaseRate {
    int hours;
    int price;

    public BaseRate(int hours, int price) {
        this.hours = hours;
        this.price = price;
    }
}

class SeasonalRate {
    BaseRate peakRate;
    BaseRate midPeakRate;
    BaseRate offPeakRate;

    public SeasonalRate(BaseRate peakRate, BaseRate midPeakRate, BaseRate offPeakRate) {
        this.peakRate = peakRate;
        this.midPeakRate = midPeakRate;
        this.offPeakRate = offPeakRate;
    }
}

class AnnualRates {
    SeasonalRate summerRate;
    SeasonalRate winterRate;

    public AnnualRates(SeasonalRate summerRate, SeasonalRate winterRate) {
        this.summerRate = summerRate;
        this.winterRate = winterRate;
    }

    public static void main(String[] args) {
        BaseRate peakWinterRateFor2019 = new BaseRate(1, 3);
        BaseRate midPeakWinterRateFor2019 = new BaseRate(1, 3);
        BaseRate offPeakWinterRateFor2019 = new BaseRate(1, 3);
        BaseRate peakSummerRateFor2019 = new BaseRate(1, 3);
        BaseRate midPeakSummerRateFor2019 = new BaseRate(1, 3);
        BaseRate offPeakSummerRateFor2019 = new BaseRate(1, 3);

        SeasonalRate winterRateFor2019 = new SeasonalRate(peakWinterRateFor2019, midPeakWinterRateFor2019, offPeakWinterRateFor2019);
        SeasonalRate summerRateFor2019 = new SeasonalRate(peakSummerRateFor2019, midPeakSummerRateFor2019, midPeakWinterRateFor2019);

        AnnualRates ratesFor2019 = new AnnualRates(summerRateFor2019, winterRateFor2019);
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=408740&siteId=1