Table of Contents

About

The Factory pattern creates an instance of an object according to a given specification, sometimes provided as arguments, sometimes inferred.

It's a dependency resolving approach. A factory class decouples the client and implementing class.

The Builder pattern is similar but is usually geared towards completing a single step along the way to the completion of an instance of a composite collection of Objects.

dependency injector framework are also factory that create not an object but a graph of object

Example

A simple factory uses static methods to get and set mock implementations for interfaces.

public class CreditCardProcessorFactory {
  
  private static CreditCardProcessor instance;
  
  public static void setInstance(CreditCardProcessor processor) {
    instance = processor;
  }

  public static CreditCardProcessor getInstance() {
    if (instance == null) {
      return new SquareCreditCardProcessor();
    }
    
    return instance;
  }
}

Name

Method

Common names for static factory methods:

  • valueOf
  • of — Popularized by EnumSet

Class

Interfaces can't have static methods, so by convention, static factory methods for an interface named Type are put in a noninstantiable class named Types.

Advantages / Disadvantages

Advantages

The advantages of static factory methods is that:

Not required to create a new object

This allows immutable classes:

  • to use preconstructed instances,
  • or to cache instances as they're constructed,

Avoid creating unnecessary duplicate objects.

Design pattern - The Singleton

a.equals(b) if and only if a==b

If a class makes this equality guarantee, then its clients can use the == operator instead of the equals(Object) method. enum types provide this equality guarantee.

Return an object of any subtype

They can return an object of any subtype of their return type. An API can return objects without making their classes public and thus Hiding implementation. With this technique, interfaces provide natural return types for static factory methods.

Disadvantage

The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed. Arguably this can be a blessing, as it encourages to use composition instead of inheritance

Documentation