【发布时间】:2014-12-05 22:11:36
【问题描述】:
tl;dr
尝试实现一个层次流畅的接口,以便我可以组合 nodes 子类,同时也可以独立使用该类,但获取类型参数不在其绑定错误范围内。
详情
我正在尝试实现一个解决方案,以便我可以创建一些东西,以便我可以执行以下操作:
farm
.animal()
.cat()
.meow()
.findsHuman()
.saysHello()
.done()
.done()
.dog()
.bark()
.chacesCar()
.findsHuman()
.saysHello()
.done()
.done()
.done()
.human()
.saysHello()
.done();
同时也能做到:
Human human = new Human()
.saysHello()
我已经使用各种策略接近了,但无法获得所描述的灵活性。
我目前的尝试使用以下类:
abstract class Base<T extends Base<T>>{
private T parent;
Base(){
}
Base( T parent ){
this.parent = parent;
}
public T done() throws NullPointerException{
if ( parent != null ){
return (T) parent;
}
throw new NullPointerException();
}
}
class Farm<T extends Base<T>> extends Base{
private Animal<Farm<T>> animal;
private Human<Farm<T>> human;
public Farm(){
super();
this.animal = new Animal( this );
this.human = new Human( this );
}
public Animal<Farm> animal(){
return this.animal;
}
public Human<Farm<T>> human(){
return this.human;
}
}
class Animal <T extends Base<T>> extends Base{
private Cat<Animal<T>> cat;
private Dog<Animal<T>> dog;
public Animal(){
super();
init();
}
public Animal( T parent ){
super( parent );
init();
}
private void init(){
this.cat = new Cat(this);
this.dog = new Dog(this);
}
public Cat<Animal<T>> cat(){
return cat;
}
public Dog<Animal<T>> dog(){
return dog;
}
}
class Human<T extends Base<T>> extends Base{
public Human<T> saysHello(){
System.out.println("human says hi");
return this;
}
}
class Cat <T extends Base<T>> extends Base{
private Human<Cat> human;
public Cat(){
super();
init();
}
public Cat( T parent ){
super( parent );
init();
}
private void init(){
this.human = new Human();
}
public Cat<T> meow(){
System.out.println("cat says meow");
return this;
}
public Human<Cat<T>> findsHuman(){
return this.human;
}
}
class Dog <T extends Base<T>> extends Base{
private Human<Dog> human;
public Dog(){
super();
init();
}
public Dog( T parent ){
super( parent );
init();
}
private void init(){
this.human = new Human();
}
public Dog<T> bark(){
System.out.println("dog says woof");
return this;
}
public Dog<T> chacesCar(){
System.out.println("cat drinks milk");
return this;
}
public Human<Dog<T>> findsHuman(){
return this.human;
}
}
我看到的错误通常是:
Animal.java:4:类型参数Animal不在其绑定的私有Cat猫内; Animal.java:5:类型参数Animal不在其绑定的私有Dog狗内;
适用于所有类似的参考文献,也适用于我的示例所需案例:
找不到符号 符号:方法狗() 位置:类 Base.dog()
我尝试使用以下似乎可以解决类似问题的解决方案,但无济于事,因此欢迎任何和所有支持。
参考文献
【问题讨论】:
-
恕我直言,您正在使用 java 泛型来实现它们的非设计。这在 C++ 中可以正常工作,但 java 泛型 不 相同。 泛型是有害的,这就是一个例子。当然,还有其他软件工程解决方案可以满足您的需求,而不是您正在粘贴的编程艺术。当事情像这里显示的答案那么复杂时,可能是出了点问题。
-
我想我找到了解决方案。我相应地更新了我的答案。
-
@AlfonsoNishikawa 我同意它可能会突破这种模式的极限,并且超出了我最初的一些理解,所以我想问问社区的想法。
-
@morpheus05 感谢您的更新,我将查看所有答案,看看是否能找到最能解决我问题的答案。
标签: java generics fluent-interface nested-generics