我是否正确实施了一个基于泛型的Java工厂? [英] Am I implementing a generics-based Java factory correctly?
本文介绍了我是否正确实施了一个基于泛型的Java工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不相信我正在实现工厂模式,因为 Application
class' createDocument
方法接受任何类型,不只是 Document的子类。
I don't believe I am implementing the factory pattern correctly because the Application
class' createDocument
method accepts any class type, not just subclasses of Document
.
换句话说,有没有办法限制 createDocument
方法只接受
In other words, is there a way I can restrict the createDocument
method to only accept subclasses of Document
?
-
Document.java
Document.java
package com.example.factory;
public abstract class Document {
public Document() {
System.out.println("New Document instance created: " + this.toString());
}
}
DrawingDocument.java
DrawingDocument.java
package com.example.factory
public class DrawingDocument extends Document {
public DrawingDocument() {
System.out.println("New DrawingDocument instance created: " this.toString());
}
}
Application.java
Application.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);
}
};
}
Main.java
Main.java
package com.example.factory;
public static void main(String[] args) {
Application application = new Application();
application.createDocument(DrawingDocument.class);
}
推荐答案
您应该绑定您的通用名称,以便它只使用T继承Document。
例子:
You should bound your generic so that it is only using T's that inherit Document. example:
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工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文