1

I have one enum each for month, quarter, and halfyear

public enum Month implements TimeInterval {

    // JAN,FEB,MAR... (all with params & constructors)

    // implementation not important
}

public enum Quarter implements TimeInterval {

    // Q1, Q2 ... (all with params & constructors)

    // implementation not important
}

public enum HalfYear implements TimeInterval {

    // HY1, HY2 (all with params & constructors)

    // implementation not important
}

and an enum with a function getIntervalByMonth(int) which I don't know how to implement.

public enum TimeIntervalUnit {

    MONTH(/* params */),

    QUARTER(/* params */),

    HALF_YEAR(/* params */);


    public TimeInterval getIntervalByMonth(int month) {
        // !!! should return the correct TimeInterval, 
        // for example TimeIntervalUnit.QUARTER.getIntervalByMonth(1) 
        // should return Quarter.Q1
    }

    // some other methods
}

I often loop over TimeIntervalUnit.values(), and inside that loop I want to use the function getIntervalByMonth(int). How can I implement this? Or can this be refactored?

4

1 回答 1

2

我建议在接口中添加boolean containsMonth(int month)方法TimeInterval。这样你可以实现TimeIntervalUnit如下:

public enum TimeIntervalUnit {

    MONTH(Month.values()),

    QUARTER(Quarter.values()),

    HALF_YEAR(HalfYear.values());


    public TimeInterval getIntervalByMonth(int month) {
        for (TimeInterval value : values) {
            if (value.containsMonth(month)) {
                return value;
            }
        }
        return null;
    }

    private final TimeInterval[] values;

    private TimeIntervalUnit(TimeInterval[] values) {
        this.values = values;
    }

    // some other methods
}
于 2013-07-24T14:25:22.400 回答