Я не верю, что правильно внедряю шаблон factory, потому что метод Application
class 'createDocument
принимает любой тип класса, а не только подклассы Document
.
Другими словами, есть ли способ, которым я могу ограничить метод createDocument
, принимать только подклассы Document
?
-
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()); } }
-
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
package com.example.factory; public static void main(String[] args) { Application application = new Application(); application.createDocument(DrawingDocument.class); }