我终于改变了最初的设计,并完全按照 Vadim Ponomarev 的建议实现了它。由于 Joda 缓冲区中的每个字段类型都有相应的 DateTimeFieldType 实例,因此我使用私有 Set 对象来跟踪存在的字段。
下面的代码显示了我是如何完成的:
private final Set<DateTimeFieldType> fieldTypes = Sets.newHashSet();
/**
* Allow to set to or reset one of the DateTimeFieldType fields
* @param fieldType the DateTimeFieldType field to change
* @param value the value to set it
*/
public void changeField(DateTimeFieldType fieldType, boolean value) {
if (value)
fieldTypes.add(fieldType);
else
fieldTypes.remove(fieldType);
}
/**
* Check if one of the DateTimeFieldType is present in this set.
* @param fieldType The field type to check for presence.
* @return true if the DateTimeFieldType is present, otherwise false
*/
public boolean isFieldSet(DateTimeFieldType fieldType) {
return !fieldTypes.contains(fieldType);
}
我还添加了一些实用方法,允许一次更改日期的所有字段和时间的所有字段。这在客户端编写代码以简化对日期字段集的常见操作时可能很有用。
/**
* Allow to set the fields that build the time part
* of a date time
* <p/>
*
* @param value value to set the DateTime fields
*/
public void changeTimeFields(boolean value) {
changeField(DateTimeFieldType.hourOfDay(), value);
changeField(DateTimeFieldType.minuteOfHour(), value);
}
/**
* Allow to set the fields that build the date part
* of a date time
* <p/>
*
* @param value value to set the DateTime fields
*/
public void changeDateFields(boolean value) {
changeField(DateTimeFieldType.dayOfMonth(), value);
changeField(DateTimeFieldType.monthOfYear(), value);
changeField(DateTimeFieldType.yearOfEra(), value);
}
最后,我还添加了一些方法来查询是否设置了所有日期字段以及是否设置了所有时间字段:
/**
* Allow to check if the DateTimeFieldType fields that build the
* date part of a datetime has been set in this instance.
* <p/>
*
* @return true if date part has yet to be applied to
* the instance, false otherwise
*/
public boolean isDateSet() {
return fieldTypes.contains(DateTimeFieldType.dayOfMonth()) &&
fieldTypes.contains(DateTimeFieldType.monthOfYear()) &&
fieldTypes.contains(DateTimeFieldType.yearOfEra());
}
/**
* Allow to check if the DateTimeFieldType fields that build the
* time part of a datetime has been set in this instance.
* <p/>
*
* @return true if time part has yet to be applied to
* the instance, false otherwise
*/
public boolean isTimeSet() {
return fieldTypes.contains(DateTimeFieldType.minuteOfHour()) &&
fieldTypes.contains(DateTimeFieldType.hourOfDay());
}
我终于把它做成了一个 DateTimeFieldTypeSet 类。我认为它很好地封装了 Joda 类中缺乏的一个常见概念。我希望它也对其他人有用。