Kin*_*isG 7 java design-patterns
我试图用帮助器方法编写一些自定义异常来设置这样的变量:
public class KeyException extends RuntimeException {
protected String Id;
protected KeyException(String message) {
super(message);
}
protected KeyException(String message, Throwable cause) {
super(message, cause);
}
public String getId() {
return keyId;
}
public KeyException withId(final String Id) {
this.Id = Id;
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在我的派生类中,我不能使用"withId"方法,因为它只返回基类 - 无论如何返回"this"指针而不必覆盖每个派生类中的方法?
无论如何返回"this"指针而不必覆盖每个派生类中的方法?
是的,请看下面的选项1.
您可以通过以下几种方式进行操作:
将结果转换为派生类
在子类中重写它
将返回类型更改为void.由于您在对象上调用方法,因此您已经有了指向它的指针.
你可以这样做:
public <T extends KeyException> T withId(final String Id) {
this.Id = Id;
return (T)this;
}
Run Code Online (Sandbox Code Playgroud)
然后在派生类中,只需将其类型作为类型参数传递.
但是可能存在设计疏忽.除了构建器模式,我很少看到setter返回对象本身的引用.如果您提供更多上下文,我们将能够为您提供更多帮助.
小智 5
使用以下构造的泛型是可能的:
public class ParentType<T extends ParentType<T>> {
public T withId(String someId) {
/* Insert other code here */
return (T) this;
}
}
public class BranchType<T extends BranchType<T>> extends ParentType<T> {}
public final class LeafTypeA extends BranchType<LeafTypeA> {}
public final class LeafTypeB extends ParentType<LeafTypeB> {}
Run Code Online (Sandbox Code Playgroud)
其中 BranchType 是有子类的类,而 LeafTypeA、LeafTypeB 是没有子类的类。
这比其他泛型解决方案略有改进,因为它可以防止:
public class LeafTypeA extends BranchType<LeafTypeB> {}
Run Code Online (Sandbox Code Playgroud)
由于这不满足类型参数的约束。
| 归档时间: |
|
| 查看次数: |
4377 次 |
| 最近记录: |