Java

Static factory vs Factory pattern

Static Factory Vs Factory Pattern

I was reading Joshua Bloch’s Effective java where he mentions that how a developer must know about using ‘Static factory’ methods for getting instance of a class. He does mention that ‘Static factory’ is not same as GOF’s standard ‘Factory pattern’. In this article I have tried to explain difference between ‘Static factory method’ and ‘Factory pattern’.

Factory Pattern

Static factory is defined as following in GOF’s book

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

In a typical Factory method implementation you create a factory class that constructs objects of a different type. 

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

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.

A static factory method is a public static method on the object that returns a new instance of the object.

With the Simple Factory, we try to abstract the creation details of the product from our caller. The only thing our caller knows, by calling a Static method and passing the desired parameter it, is that it returns an object of the type

So whenever there are chances to create many implementations of a product go for the Simple factory.

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

References

Read this DZone article.

Related posts
Java

How to create singleton class in Java?

Java

Intro to static factory methods and when should you prefer static methods over Constructors?

Java

Introduction to JVM and its internals

Leave a Reply

Your email address will not be published. Required fields are marked *

Join The Club!

Be the first to learn about
our amazing Articles

let's Learn together