Ich glaube nicht, dass ich das Fabrikmuster richtig implementiere, weil die Application
Klasse' createDocument
Methode akzeptiert jeden Klassentyp, nicht nur Unterklassen von Document
.
Mit anderen Worten, gibt es eine Möglichkeit, die createDocument
Methode, um nur Unterklassen von Document
?
-
Dokument.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()); } }
-
Anwendung.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); }