Factory Method Design Pattern Java Simple Detailed Examples

Factory Method Design Pattern Java

Factory Method design pattern also known as “Virtual Constructor” is a part of Gang of Four Creational Design Pattern. Factory Method design pattern is used when we have a superclass with multiple subclasses and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of instantiation of a class from the client program to the factory class.

The factory method pattern makes use of classes that acts as factories to create objects. This pattern favors method invocation instead of making direct constructor calls to create objects.
In the factory method pattern, we provide an interface, which can be a Java interface or an abstract class to create objects. A Factory class will be responsible for creating and returning an object of child class requested by the client.

A factory method pattern is one of the core design principles to create an object. This allows clients to create objects of a library in a way such that it doesn’t have tight coupling with the class hierarchy of the library.

This tutorial is a part of Creational Design Pattern Series. Take a look at other Creational Design Patterns:

  1. Singleton Creational Design Pattern Java Explained [6 Code Example]
  2. Factory Design Pattern Java Simplified [Simple Real World Example]
  3. Factory Method Design Pattern Java Simple Detailed Examples
  4. Abstract Factory Design Pattern Java Real World Example
  5. Builder Design Pattern Java Real World Example
  6. Prototype Design Pattern Java Real World Example

 

Factory Method Design Pattern Implementation

In our example, we will implement a logic to make a transaction in the Stock Exchange. In here, Client will have to call only the Factory method with the listed company name to get the Company specific class. All inside class creation logic will be hidden from the client.

All About Java Regular Expressions Regex 2019

A Super-Class (Interface or Abstract Class)

Factory Method Design Pattern requires to have a Super Class which will be extended or inherited by the final product subclasses. In our example, we are using an abstract class Stock which has two abstract methods, buyShares(), and sellShares().

 

package com.adevguide.java.designpatterns.factorymethod;


public abstract class Stock {

    public Stock() {
        System.out.println("You are making Transactions at NASDAQ");
    }

    public abstract void buyShares(int n);

    public abstract void sellShares(int n);

}

 

Sub-Classes

We have implemented three subclasses: AppleStock, AmazonStock, and GoogleStock. All subclasses have to implement superclass unimplemented classes. The implementation logic of these methods can be anything; only specific to class.

package com.adevguide.java.designpatterns.factorymethod;

public class AppleStock extends Stock {

    @Override
    public void buyShares(int n) {

        System.out.println("Congrats!! You have successfully bought " + n + " Apple Shares.");
    }

    @Override
    public void sellShares(int n) {
        System.out.println("Congrats!! You have successfully sold " + n + " Apple Shares.");

    }

}

 

package com.adevguide.java.designpatterns.factorymethod;


public class AmazonStock extends Stock {

    @Override
    public void buyShares(int n) {
        System.out.println("Congrats!! You have successfully bought " + n + " Amazon Shares.");

    }

    @Override
    public void sellShares(int n) {
        System.out.println("Congrats!! You have successfully sold " + n + " Amazon Shares.");

    }

}

 

package com.adevguide.java.designpatterns.factorymethod;


public class GoogleStock extends Stock {

    @Override
    public void buyShares(int n) {
        System.out.println("Congrats!! You have successfully bought " + n + " Google Shares.");

    }

    @Override
    public void sellShares(int n) {
        System.out.println("Congrats!! You have successfully sold " + n + " Google Shares.");

    }

}

 

Abstract Factory Class

SuperStockFactory is an Abstract class Factory.

package com.adevguide.java.designpatterns.factorymethod;

public abstract class SuperStockFactory {
    
    public abstract Stock getStock(StockCompany company);

}

 

Concrete Factory Class

Concrete Factory Class AmazonFactory, GoogleFactory, AppleFactory  are implementations of Abstract Factory class.

package com.adevguide.java.designpatterns.factorymethod;

public class AmazonFactory extends SuperStockFactory {

    @Override
    public Stock getStock() {
        return new AmazonStock();
    }

}
package com.adevguide.java.designpatterns.factorymethod;

public class AppleFactory extends SuperStockFactory {

    @Override
    public Stock getStock() {
        return new AppleStock();
    }

}
package com.adevguide.java.designpatterns.factorymethod;

public class GoogleFactory extends SuperStockFactory {

    @Override
    public Stock getStock() {
        return new GoogleStock();
    }

}

The factory method getStock() returns concrete class of respective stock.

 

Client Class

Let’s create a Client that will demonstrate the implementation of the factory method design pattern.

package com.adevguide.java.designpatterns.factorymethod;

public class Client {

    public static void main(String[] args) {

        try {
            Stock appleStock = new AppleFactory().getStock();
            appleStock.buyShares(10);

            System.out.println("********************************");
            Stock amazonStock = new AmazonFactory().getStock();
            amazonStock.sellShares(20);

            System.out.println("********************************");
            Stock googleStock = new GoogleFactory().getStock();
            googleStock.buyShares(30);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

Output:

You are making Transactions at NASDAQ
Congrats!! You have successfully bought 10 Apple Shares.
********************************
You are making Transactions at NASDAQ
Congrats!! You have successfully sold 20 Amazon Shares.
********************************
You are making Transactions at NASDAQ
Congrats!! You have successfully bought 30 Google Shares.

Notice that client is calling stock specific concrete factory class which inturn will return concrete stock class.

All About Java Regular Expressions Regex 2019

When to use the Factory Method Design Pattern?

  • We can use this design when we want to delegate object instantiation to subclass. We would want to do this when we have product inheritance hierarchy and the possibility of the future addition to that.

Advantages of using Factory Method Design Pattern

  1. Factory Method Design pattern provides an approach to code for interface rather than implementation.
  2. Factory Method Design pattern allows the sub-classes to choose the type of objects to create.
  3. Factory Method Design pattern promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.
  4. That means the code interacts solely with the resultant interface or abstract class so that it will work with any classes that implement that interface or that extends that abstract class. For example, we can easily change AppleStock class implementation because the client program is unaware of this.
  5. Factory pattern provides abstraction between implementation and client classes through inheritance.

 

Pitfalls of using Factory Method Design Pattern

  • We have to start with the Factory Method Design Pattern form the inception of the application. It is not easy to refactor an existing application code into the Factory method pattern.
  • Factory Method Design Pattern pattern is more complex to implement. Due to code to interface design, It requires more classes which will need unit testing.
  • Code to the interface is required for this design, due to which the pattern forces to subclass just to create an appropriate instance.

Real-World Example of Factory Method Design Pattern

  • java.util.Collection has an abstract an abstract method called iterator().  This method is an example of JDK implementation of Factory Method Design Pattern.

 

Factory Method Design Pattern Source Code

The complete source code of this tutorial is available in our GitHub repository.

Source Code GitHub Link

 

References

https://www.oodesign.com/factory-method-pattern.html