gpt4 book ai didi

java - 我是否正确地实现了基于泛型的 Java 工厂?

转载 作者:太空狗 更新时间:2023-10-29 23:03:20 26 4
gpt4 key购买 nike

我认为我没有正确实现工厂模式,因为 Application 类的 createDocument 方法接受任何类类型,而不仅仅是 Document< 的子类.

换句话说,有没有办法限制 createDocument 方法只接受 Document 的子类?

  • 文档.java

    package com.example.factory;

    public abstract class Document {
    public Document() {
    System.out.println("New Document instance created: " + this.toString());
    }
    }
  • DrawingDocument.java

    package com.example.factory

    public class DrawingDocument extends Document {
    public DrawingDocument() {
    System.out.println("New DrawingDocument instance created: " this.toString());
    }
    }
  • 应用程序.java

    package com.example.factory;

    public class Application {
    public <T> T createDocument(Class<T> documentClass) {
    try {
    return documentClass.newInstance();
    } catch (InstantiationException e) {
    throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
    throw new IllegalArgumentException(e);
    }
    };
    }
  • 主.java

    package com.example.factory;

    public static void main(String[] args) {
    Application application = new Application();
    application.createDocument(DrawingDocument.class);
    }

最佳答案

你应该 bound您的泛型,以便它仅使用继承 Document 的 T。示例:

public class Application {
//Add extends Document after T
public static <T extends Document> T createDocument(Class<T> documentClass) throws InstantiationException, IllegalAccessException {
return documentClass.newInstance();
};
}

关于java - 我是否正确地实现了基于泛型的 Java 工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6191710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com