Design Pattern - (Static) Factory

> Code - (Programming|Computer) Language > Design Pattern

1 - 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.

Advertising

3 - 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;
  }
}

4 - Name

4.1 - Method

Common names for static factory methods:

  • valueOf
  • of — Popularized by EnumSet

4.2 - 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.

5 - Advantages / Disadvantages

5.1 - Advantages

The advantages of static factory methods is that:

Advertising

5.1.1 - 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.

5.1.2 - 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.

5.2 - 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

6 - Documentation

Advertising