我很难创建类型安全行为,我将使用一个一般示例来强调我的问题:
我有一个界面BoxCreator
其定义为:
public interface BoxCreator{
public Box create(int id ,List<Box> others);
}
和一般Box
类(A Box
可以包含其他几个 Box
es),其具有类似 int getId()
的方法, Box getInternalBox(int id)
.
假设我有一个类Shed implements BoxCreator,Container
(其中容器只是一个通用接口(interface),具有添加和删除等操作)。我可以把新东西放进棚子里,它会把它们装在 ShedBox
中。它实现了 Box
.
到目前为止一切顺利,当我尝试创建一些其他类来做一些不同的事情时,问题就出现了,例如 CoolShed extends Shed implements BoxCreator
它将把东西放入 CoolBox
es(扩展 ShedBox
)。
目前它可以工作,但我在 CoolShed
中有几个向下转换类(从一般 Box
到 CoolBox
)可能“不漂亮”。
我正在寻找的是一种制作方法
Shed<T extends ShedBox> implements BoxCreator<T>
然后在执行 CoolShed
时我只想做类似的事情
CoolShed extends Shed<CoolBox> implemets BoxCreator<CoolBox>
我试图使各种类通用,但无法创建通用的 create
方法,因为我无法实例化 T
或为此退回一份。所以我有点迷失。
一些注意事项:
CoolShed
使用了很多Shed
逻辑,但我只是让它使用CoolBox
类作为容器。- 目前
Shed
有一个BoxCreator
的实例所以在创建CoolShed
时我只是做CoolShed
新的创建者并且它有效。 -
CoolShed
只会有CoolBox
实例,但我真的不介意任何扩展ShedBox
在Shed
类。
我只是找不到如何实现所需行为的良好解释,也无法判断我现有的 Actor 阵容是否合适。
我知道我的示例很长,我很乐意尽我所能使其更清楚。
编辑
使问题更清晰的代码模板:
public interface BoxCreator{
public Box create(int id ,List<Box> others);
}
public interface Box{
void put()
void addAnother(Box box);
}
public class ShedBox implements Box{
void put()
void addAnother(Box box);
}
public class CoolBox extends ShedBox{ //has some extra features but moslty the same
void put()
void addAnother(Box box);
}
public interface Container {
Box addValue(int value);
Box getBox(int id);
.
.
}
public class Shed implements Container, BoxCreator {
BoxCreator creator;
SomeCollection<Box> boxes;
Shed(){
creator = this;
.
.
.
}
Box addValue(int id){
.
.//some logic to get otherBox here
.
Box box = creator.createBox(id,otherBox);
}
Box getBox(int id);
public Box create(int id ,Box other){
return new ShedBox(id,others)
}
}
public class CoolShed extends Shed implements BoxCreator {
CoolShed(){
creator = this;
.
.
.
}
addValue(int id){
Box boxAdded = super.add(id)
.
.
.
CoolBox box = (CoolBox)boxAdded; // The questionable cast
.
. //Some logic that involves CoolBox specific actions
.
}
public Box create(int id ,Box other){
return new CoolBox(id,others)
}
}
最佳答案
(之前的答案已删除)
编辑:这个解决方案应该更好,假设others
可能包含任何框:
public interface BoxCreator {
public Box create(int id, List<Box> others);
}
public class Shed implements BoxCreator {
@Override
public ShedBox create(int id, List<Box> others) {
...
}
}
public class CoolShed extends Shed {
@Override
public CoolBox create(int id, List<Box> others) {
...
}
}
另外,不要这样做:
BoxCreator creator;
creator = this;
creator.create(...);
相反,您应该编写 this.create(...)
或简单地编写 create(...)
。然后,您不必从 Box
转换为所需的子类,因为从 create
返回的值已经是 ShedBox
或 CoolBox
.
关于java - 如何从具有通用返回类型的方法返回实际实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16594590/