目前我有这个实现了 Builder 模式的类,为了便于阅读,我选择省略一些方法,更准确地说,我只展示了username
.
package dao.constraint;
import java.util.Arrays;
public class AccountConstraint {
private Constraint<Range<Integer>> accountIdConstraint;
private Constraint<String> usernameConstraint;
private Constraint<String> passwordConstraint;
private Constraint<String> emailConstraint;
private AccountConstraint(Builder builder) {
this.accountIdConstraint = builder.accountIdConstraint;
this.usernameConstraint = builder.usernameConstraint;
this.passwordConstraint = builder.passwordConstraint;
this.emailConstraint = builder.emailConstraint;
}
public Constraint<Range<Integer>> getAccountIdConstraint() {
return accountIdConstraint;
}
public Constraint<String> getUsernameConstraint() {
return usernameConstraint;
}
public Constraint<String> getPasswordConstraint() {
return passwordConstraint;
}
public Constraint<String> getEmailConstraint() {
return emailConstraint;
}
public Constraint[] getConstraints() {
return Arrays.asList(this.getAccountIdConstraint(), this.getUsernameConstraint(), this.getPasswordConstraint(), this.getEmailConstraint()).toArray(new Constraint[4]);
}
public static class Builder {
private Constraint<Range<Integer>> accountIdConstraint;
private Constraint<String> usernameConstraint;
private Constraint<String> passwordConstraint;
private Constraint<String> emailConstraint;
public Builder() {
this.accountIdConstraint = null;
this.usernameConstraint = null;
this.passwordConstraint = null;
this.emailConstraint = null;
}
public Builder username(final String username) {
this.usernameConstraint = new Constraint<>(Operation.IS, true, username, "username");
return this;
}
public Builder notUsername(final String username) {
this.usernameConstraint = new Constraint<>(Operation.IS, false, username, "username");
return this;
}
public Builder usernameLike(final String username) {
this.usernameConstraint = new Constraint<>(Operation.LIKE, true, username, "username");
return this;
}
public Builder usernameNotLike(final String username) {
this.usernameConstraint = new Constraint<>(Operation.LIKE, false, username, "username");
return this;
}
public AccountConstraint build() {
return new AccountConstraint(this);
}
}
}
如您所见,AccountConstraint.Builder.username(String s)
和之间有非常细微的区别AccountConstraint.Builder.notUsername(String s)
。
我希望能够写出类似的东西new AccountConstraint.Builder().not(username(s));
。username(String s)
但是,据我所知,如果未在调用 Java 类中定义,则这不是有效的 Java 语法。我不想再重复整个AccountConstraint.Builder()
过程来达到username(String s)
部分。有什么解决办法吗?
第二个问题:可以AccountConstraint.getConstraints()
改进还是写得更简单?
问候。