MTI TEK
  • Home
  • About
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All Resources
Design Patterns | Factory Method
  1. References
  2. Example
    • The Product
    • The Concrete Product
    • The Factory
    • A simple class to test the Factory Method design pattern

  1. References
    • Definition: (source: http://en.wikipedia.org/wiki/Factory_method_pattern)

      Define an interface for creating an object, but let subclasses decide which class to instantiate.
      The Factory method lets a class defer instantiation it uses to subclasses.
  2. Example
    • The Product:

      public interface Report {
          public String generate(final String data);
      }

    • The Concrete Product:

      public class ReportHtml implements Report {
          public String generate(final String csvData) {
              final StringBuilder htmlData = new StringBuilder();
      
              if (csvData != null) {
                  final String[] dataElements = csvData.split(",");
      
                  for (final String dataElement : dataElements) {
                      htmlData.append(String.format("<b>%s</b>", dataElement));
                  }
              }
      
              return htmlData.toString();
          }
      }

    • The Factory:

      public class ReportFactory {
          public static Report getReport(final String type) {
              if ("html".equalsIgnoreCase(type)) {
                  return new ReportHtml();
              }
      
              return null;
          }
      }

    • A simple class to test the Factory Method design pattern:

      public class FactoryMethodPatternTest {
          public static void main(String[] args) {
              // create the report
              final Report report = ReportFactory.getReport("html");
      
              // call methods
              final String htmlReport = report.generate("1,abc");
      
              System.out.println(htmlReport);
          }
      }

© 2025 mtitek