Static Factory Method Pattern

The factory method is a pattern used to create objects of a certain type without an constructor. When looking at examples around the internet I saw so many different examples I was actually shocked. We are going to look at one way to build the pattern, and I sum up a list of different type of implementations I have seen for this.

First we create an abstract base class (the functionality is crap, but we are not her for that).

public abstract class Product {

    protected String name;

    protected Product() {


    public Product(String name) { = name;

    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +

Then we create a few classes that extend this class.

public class Shoarma extends Product {

    public Shoarma() {
        name = "Shoarma";

public class Tzaziki extends Product {

    public Tzaziki() {
        name = "Tzaziki";

public class Pita extends Product {

    public Pita() {
        name = "Pita";

public class Gyros extends Product {

    public Gyros() {
        name = "Gyros";

Finally we create our factory.

public class ProductFactory {

    private static final Map<String,Product> products = new HashMap<>();

    public static Product CreateProduct(String name){
        return products.get(name);

    private static void fillProductsList(){
        products.put("Shoarma", new Shoarma());
        products.put("Gyros", new Gyros());
        products.put("Pita", new Pita());
        products.put("Tzaziki", new Tzaziki());

Then we use our classes.

public static void main(String[] args) {
    Product p = ProductFactory.CreateProduct("Shoarma");
    System.out.println(p +" "+ p.hashCode());

    Product p1 = ProductFactory.CreateProduct("Shoarma");
    System.out.println(p +" "+ p1.hashCode());

This gives us the following output.

Product{name='Shoarma'} 356573597
Product{name='Shoarma'} 1735600054

The factory create new classes through lookup in the map. It creates a new object every time. You can change this by instantiating the map in static{} so you only have one instance of your class.

There are a few more ways that people create static factory methods:

  • With if-else or switch instead of lookup.
  • With reflection.
  • With enums instead of string, so it’s type safe.

And of course combinations of all of the way’s above. I picked this way to show because:

  • I know all the class, so it’s not yet necessary to use an enum.
  • All new classes now only need to be added to the fillProductsList, which keeps my code easy to manage.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s