您好,登錄后才能下訂單哦!
在Java中,Calendar類可以用于計算工作日,即排除周末和節假日。為了提高可擴展性,可以采用以下設計:
public interface HolidayCalendar {
boolean isHoliday(Calendar date);
}
public class DefaultHolidayCalendar implements HolidayCalendar {
@Override
public boolean isHoliday(Calendar date) {
// 實現節假日判斷邏輯
return false;
}
}
public class CustomHolidayCalendar implements HolidayCalendar {
@Override
public boolean isHoliday(Calendar date) {
// 實現自定義節假日判斷邏輯
return false;
}
}
public class WorkdayCalculator {
public int calculateWorkdays(Calendar startDate, Calendar endDate, HolidayCalendar holidayCalendar) {
int workdays = 0;
Calendar current = (Calendar) startDate.clone();
while (current.before(endDate)) {
if (current.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && current.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
&& !holidayCalendar.isHoliday(current)) {
workdays++;
}
current.add(Calendar.DAY_OF_MONTH, 1);
}
return workdays;
}
}
public class Main {
public static void main(String[] args) {
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DAY_OF_MONTH, 10);
HolidayCalendar holidayCalendar = new DefaultHolidayCalendar();
WorkdayCalculator calculator = new WorkdayCalculator();
int workdays = calculator.calculateWorkdays(startDate, endDate, holidayCalendar);
System.out.println("工作日:" + workdays);
}
}
通過上述設計,可以輕松地擴展節假日計算方法,提高代碼的靈活性和可維護性。同時,還可以根據具體業務需求實現不同的節假日判斷邏輯。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。