一、问题现状
日期转换,先尝试进行转换,如果失败了,则在前面拼接一个1再尝试转换,如果还失败,则返回空,下面处理try-catch嵌套了太多层。
try {
return D_MMMM_YYYY.parse(s, LocalDate::from);
} catch (DateTimeParseException e) {
try {
s = "1 " + s;
return D_MMMM_YYYY.parse(s, LocalDate::from);
} catch (DateTimeParseException ee) {
log.error("Failed to parse date: " + olds);
return null;
}
}
二、责任链模式改造
1. 责任链处理器接口interface
public interface DateParserChain {
/**
* 解析日期字符串
* @param dateStr
* @return
*/
LocalDate parse(String dateStr);
/**
* 设置下一个处理器
* @param next
* @return 下一个处理器
*/
DateParserChain setNext(DateParserChain next);
}
2. 责任链处理器的抽象实现
abstract class BaseDateParserChain implements DateParserChain {
private DateParserChain next;
@Override
public DateParserChain setNext(DateParserChain next) {
this.next = next;
return next;
}
protected LocalDate parseNext(String s) {
if (next != null) {
return next.parse(s);
}
return null;
}
}
3. 时间转换工具类
public class DateParser {
private static DateParserChain dateParserChain;
static {
// 构造处理链
dateParserChain = new OnlyYearDateParser();
DateParserChain hasDateParseChain = dateParserChain.setNext(new HasDateParser());
DateParserChain noDateParseChain = hasDateParseChain.setNext(new NoDateParser());
DateParserChain normalDateParseChain = noDateParseChain.setNext(new NormalDateParser());
}
//具体转换方法 - 工具方法 DateParser.parseDate()
public static LocalDate parseDate(String dateStr) {
LocalDate date = dateParserChain.parse(dateStr);
if (date == null) {
logger.error("Failed to parse date: {}", dateStr);
}
return date;
}
//第一链
static class OnlyYearDateParser extends BaseDateParserChain {
@Override
public LocalDate parse(String s) {
// 具体方法略
return parseNext(s);
}
}
//第二链
static class HasDateParser extends BaseDateParserChain {
private final DateTimeFormatter D_MMMM_YYYY = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.ENGLISH);
@Override
public LocalDate parse(String s) {
try {
// 具体方法略
} catch (DateTimeParseException e) {
return parseNext(s);
}
}
}
//第三链
static class NoDateParser extends BaseDateParserChain {
private final DateTimeFormatter D_MMMM_YYYY = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.ENGLISH);
@Override
public LocalDate parse(String s) {
try {
// 具体方法略
} catch (DateTimeParseException e) {
return parseNext(s);
}
}
}
//第四链
static class NormalDateParser extends BaseDateParserChain {
private final DateTimeFormatter M_D_YYYY = DateTimeFormatter.ofPattern("M/d/yyyy");
@Override
public LocalDate parse(String s) {
try {
// 具体方法略
} catch (DateTimeParseException e) {
return parseNext(s);
}
}
}
}