我想使用构建器模式来创建未知对象
该怎么做?
我的代码如下:
public abstract class abstractA<T extends GameApplication<T>>{
public static class Builder<T> {
private JPanel panel = new JPanel();
private JFrame frame = new JFrame();
private int height = 0, width = 0;
private int x = 0,y = 0;
private Color backgroundColor = Color.BLUE;
public Builder setFrameHeightWidth(int height, int weight) {
this.height = height;
this.width = weight;
return this;
}
public Builder setLocation(int x, int y) {
this.x = x;
this.y = y;
return this;
}
public Builder setbackground(Color color) {
this.backgroundColor = color;
return this;
}
public T Build(){
//error here
return new T ;
}
}
我想这样使用它:
class RealA extends abstractA{
public static void main(String[] argv){
RealA a = abstractA.builder
.setLocation(100,200)
.setFrameHeightWidth(500,600)
.build();
}
}
并且我无法创建泛型对象,但是我需要这个。该怎么做?
答案 0 :(得分:0)
如果让构建器知道它正在构建的事物(通过将其传递给一个类),然后让其使用反射来创建实例,则可以进行类似的操作(类似) (例如类newInstance
方法)。
这假定所有子类都具有零参数构造函数。 (可以修改为使用带有参数的构造函数,但是每个子类都需要具有相同签名的构造函数)
例如...
public class Stack {
static abstract class Common {
protected String name;
public void setName(String name) {
this.name = name;
}
public abstract void doSomething();
}
static class Solid1 extends Common {
@Override
public void doSomething() {
System.out.println("Solid1's implementation: name=" + name);
}
}
static class Solid2 extends Common {
@Override
public void doSomething() {
System.out.println("Solid2's implementation: name=" + name);
}
}
static class Builder<T extends Common> {
private final Class<T> clazz;
private String name;
public Builder(Class<T> clazz) {
this.clazz = clazz;
}
public Builder<T> setName(String name) {
this.name = name;
return this;
}
public T build() {
T t;
try {
t = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException("Bad things have happened!");
}
t.setName(name);
return t;
}
}
public static void main(String[] args) {
Solid1 solid1 = new Builder<>(Solid1.class).setName("[NAME]").build();
Solid2 solid2 = new Builder<>(Solid2.class).setName("[NAME]").build();
solid1.doSomething();
solid2.doSomething();
}
}
输出...
Solid1's implementation: name=[NAME]
Solid2's implementation: name=[NAME]
不确定这有什么用...