我试图创建一个Box<T>
类.它应该有两个公共不可变(val
)属性,isContentMandatory: Boolean
content: T?
.这是我想要接受的值的组合:
isContentMandatory | content | Should allow? |
---|---|---|
false | null | YES |
false | non-null | YES |
true | null | NO |
true | non-null | YES |
我想确保我提供的构造函数不会允许对象的非法状态.此外,我需要多个构造函数(或使用默认值),以便为客户端创建一个对象是straight-forward.以下是实例化示例:
Box() // OK -> isContentMandatory = false, content = null
Box("some-content") // OK -> isContentMandatory = false, content = "some-content"
Box(false, "some-content") // OK -> isContentMandatory = false, content = "some-content"
Box(true, "some-content") // OK -> isContentMandatory = true, content = "some-content"
Box(true, null) // DON'T ALLOW
Box(true) // DON'T ALLOW
如果可能的话,最好在编译时禁止使用上面的DON'T ALLOW
(没有用于该组合的构造函数).否则,在创建过程中异常失败.
我来自Java世界,所以所有这些主要/次要构造函数、默认值等都有点模糊,所以请解释一下并给出解决方案.如果不同的类设计支持相同的业务逻辑,我也会接受.
EDIT:这就是它在Java中的外观.
public class Box<T> {
private final boolean isContentMandatory;
private final T content;
public Box() {
this(null);
}
public Box(T content) {
this(false, content);
}
public Box(boolean isContentMandatory, T content) {
if (isContentMandatory && content == null) {
throw new IllegalArgumentException("Invalid combination of parameters");
}
this.isContentMandatory = isContentMandatory;
this.content = content;
}
...getters...
}