您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。