Benefits of Factory Pattern

  • The factory pattern decoupling or the dependencies between the calling code and called objects like Circle, Square etc. Factory pattern returns an instance of several (product hierarchy) subclasses (like Circle, Square etc), but the calling code is unaware of the actual implementation class. The calling code invokes the method on the interface (for example Shape) and using polymorphism the correct draw() method gets invoked.
  • You do not have to create a new Circle or a new Square on each invocation as shown in the sample code, which is for the purpose of illustration and simplicity. In future, to conserve memory you can decide to cache objects or reuse objects in your factory with no changes required to your calling code. You can also load objects in your factory based on attribute(s) read from an external properties file or some other condition.
  • Another benefit going for the factory is that unlike calling constructors directly, factory patterns have more meaningful names like getShape(…), getInstance(…) etc, which may make calling code more clear.