我正在创建一个构建器类,我希望在按域对象创建时向用户提供2个流。
我的域对象看起来像
public class Comparator<T> {
private Map<String, ReflectionComparatorMode> includedFields;
private List<String> excludedFields;
private T expected;
private T actual;
//getters
}
我的建造者看起来像
public static class ComparatorBuilder<T> {
private Map<String, ReflectionComparatorMode> includedFields;
private List<String> excludedFields;
private T expected;
private T actual;
public ComparatorBuilder(T expected, T actual) {
this.expected = expected;
this.actual = actual;
includedFields = new HashMap<String, ReflectionComparatorMode>();
}
public ComparatorBuilder<T> includeFieldsInStrictMode(String fieldName) {
this.includedFields.put(fieldName, null);
return this;
}
public ComparatorBuilder<T> includeFieldsInStrictMode(List<String> fieldNames) {
for (String fieldName : fieldNames) {
this.includedFields.put(fieldName, null);
}
return this;
}
public ComparatorBuilder<T> includeFieldsInLenientOrderMode(String fieldName) {
this.includedFields.put(fieldName, ReflectionComparatorMode.LENIENT_ORDER);
return this;
}
public ComparatorBuilder<T> includeFieldsInLenientOrderMode(List<String> fieldNames) {
for (String fieldName : fieldNames) {
this.includedFields.put(fieldName, ReflectionComparatorMode.LENIENT_ORDER);
}
return this;
}
public ComparatorBuilder<T> includeFieldsInLenientDateMode(String fieldName) {
this.includedFields.put(fieldName, ReflectionComparatorMode.LENIENT_DATES);
return this;
}
public ComparatorBuilder<T> includeFieldsInLenientDateMode(List<String> fieldNames) {
for (String fieldName : fieldNames) {
this.includedFields.put(fieldName, ReflectionComparatorMode.LENIENT_DATES);
}
return this;
}
public ComparatorBuilder<T> includeFieldsInIgnoreDefaultMode(String fieldName) {
this.includedFields.put(fieldName, ReflectionComparatorMode.IGNORE_DEFAULTS);
return this;
}
public ComparatorBuilder<T> includeFieldsInIgnoreDefaultMode(List<String> fieldNames) {
for (String fieldName : fieldNames) {
this.includedFields.put(fieldName, ReflectionComparatorMode.IGNORE_DEFAULTS);
}
return this;
}
public ComparatorBuilder<T> excludedFields(List<String> fieldNames) {
this.excludedFields.addAll(fieldNames);
return this;
}
public Comparator<T> build() {
Comparator<T> comparator = new Comparator<T>();
comparator.actual = this.actual;
comparator.expected = this.expected;
comparator.includedFields = this.includedFields;
comparator.excludedFields = this.excludedFields;
return comparator;
}
现在我不希望调用者能够使用excludedFields方法,如果它调用任何includedMethods(...),并且类似地如果它使用excludedFields它不应该能够调用任何包含的方法。它应该能够直接调用构建方法。
如何使用构建器模式或步骤构建器实现此目的?