Why is the Factory Method So Glorious?

The Factory Method (FM)’s intent is for interfacing object creation and allowing subclasses to defer which type to create. The main benefit for doing so is to avoid class dependencies by direct calls to a particular constructor. Since constructors are not considered methods and not available for overriding, FM’s gives us this option.


Two Variations

There are two variations of implementing the FM:
Default Implementation
Simple Factory

Default Implementation

 public Product makeProduct(){
                return new DefaultProduct();
             }
            

Simple Factory

public Product makeProduct(Type type){
                 if(type.equals("A") return new ProductA();
                 if(type.equals("B") return new ProductB();
                 .
                 .
                 .
                 throw new NoSuchProductTypeException();
            }
            

`


TL:DR?

The key criteria for a FM are:

  • returning a new object
  • return a new instance of a type
  • possibly be implemented by several classes
  • For a FM found in the wild, check out Java's Collection.iterator() [Notice how it returns a new instance of a type and is subclassed].