Am I implementing a generics-based Java factory correctly?

后端 未结 3 1363
青春惊慌失措
青春惊慌失措 2021-02-05 14:40

I don\'t believe I am implementing the factory pattern correctly because the Application class\' createDocument method accepts any class type, not just

相关标签:
3条回答
  • 2021-02-05 14:58

    The code looks good. In a real implementation the factory method should not be declared to throw any of the reflection-related exceptions. And you will probably have some different code anyway to create the document.

    The faxtory method should take a Class<? extends Document> as its parameter, so that one cannot ask it to create a String, for example.

    [update:] Code sample:

    public Document createDocument(Class<? extends Document> clazz) {
      try {
        return clazz.newInstance();
      } catch (InstantiationException e) {
        throw new IllegalArgumentException(e);
      }
    }
    
    0 讨论(0)
  • 2021-02-05 15:07

    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();
        };
    }
    
    0 讨论(0)
  • 2021-02-05 15:09

    Where is the restriction to Document type in the factory ? Try

    public <T extends Document> T createDocument(Class<T> documentClass) throws InstantiationException, IllegalAccessException {
        return documentClass.newInstance();
    };
    
    0 讨论(0)
提交回复
热议问题