instance factory methods Vs Static factory methods

user2434 picture user2434 · Nov 16, 2011 · Viewed 34.6k times · Source

Can't all factory methods be static ? Does something that produces a product need state ? When is it appropriate to go for a instance factory or static factory method ? Can you provide me examples differentiating the two ?

Answer

Ramon Chiara picture Ramon Chiara · Dec 9, 2012

Assuming that by "instance factory method" you're actually saying about the GoF "factory method", the term "static factory method" is described by Joshua Bloch in his book "Effective Java". Googling around I reached at these sites:

Hope that it helped to make the difference a little bit clearer.

Following Marvo's advice:

  • Factory Method as stated in GoF:

    define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Example (Java code):

    public abstract class Product { ... }

    public class ConcreteProduct extends Product { ... }

    public abstract class Creator {
      public void anOperation() { ... product = factoryMethod(); ... }
      public abstract Product factoryMethod();
    }

    public class ConcreteCreator extends Creator {
      public Product factoryMethod() { return new ConcreteProduct(); }
    }
  • Static Factory Method as stated in Effective Java:

    A class can provide a public static factory method, which is simply a static method that returns an instance of the class. (...) One advantage of static factory methods is that, unlike constructors, they have names. (...) A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked. (...) A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. (...) The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.

Example (Java code):

    public class Boolean {
      ...
      public static Boolean valueOf(boolean b) {
        return b ? Boolean.TRUE : Boolean.FALSE;
      }
      ...
    }