AdrianHu99 / NOTES

0 stars 0 forks source link

java design pattern 詳說 #63

Closed AdrianHu99 closed 4 years ago

AdrianHu99 commented 4 years ago

https://mp.weixin.qq.com/s/JADbDngTuLIy5ZnxFESLGA

AdrianHu99 commented 4 years ago

项目开发阶段,有一个关于下单发货的需求:如果今天下午3点前进行下单,那么发货时间是明天,如果今天下午3点后进行下单,那么发货时间是后天,如果被确定的时间是周日,那么在此时间上再加1天为发货时间。

仔细考虑如何写代码,然后再去写,不是说所有的时间操作都用Calendar或Date去解决,一定要看场景。

对于时间的计算我们要考虑joda-time这种类似的成熟时间计算框架来写代码,它会让代码更加简洁和易读。

AdrianHu99 commented 4 years ago
final DateTime DISTRIBUTION_TIME_SPLIT_TIME = new DateTime().withTime(15,0,0,0);
private Date calculateDistributionTimeByOrderCreateTime(Date orderCreateTime){
    DateTime orderCreateDateTime = new DateTime(orderCreateTime);
    Date tomorrow = orderCreateDateTime.plusDays(1).toDate();
    Date theDayAfterTomorrow = orderCreateDateTime.plusDays(2).toDate();
    return orderCreateDateTime.isAfter(DISTRIBUTION_TIME_SPLIT_TIME) ? wrapDistributionTime(theDayAfterTomorrow) : wrapDistributionTime(tomorrow);
}
private Date wrapDistributionTime(Date distributionTime){
    DateTime currentDistributionDateTime = new DateTime(distributionTime);
    DateTime plusOneDay = currentDistributionDateTime.plusDays(1);
    boolean isSunday = (DateTimeConstants.SUNDAY == currentDistributionDateTime.getDayOfWeek());
    return isSunday ? plusOneDay.toDate() : currentDistributionDateTime.toDate() ;
}
AdrianHu99 commented 4 years ago

image

AdrianHu99 commented 4 years ago

lombok is very useful and making code much cleaner

AdrianHu99 commented 4 years ago

如果你是一个优秀的java程序员,请为你想做的抽象接口,做好泛型吧。