0

我想使用构建器模式来创建未知对象

怎么做?

我的代码是这样的:

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();
}

}

而且我无法创建泛型对象,但我需要这个。怎么做?

4

1 回答 1

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]

不知道这有多大用...

于 2019-04-18T16:13:47.353 回答