Factory method design pattern in Java

It is a creational design pattern which talks about the creation of an object. The factory design pattern says that define an interface ( A java interface or an abstract class) and let the subclasses decide which object to instantiate. The factory method in the interface lets a class defer the instantiation to one or more concrete subclasses. Since this design patterns talk about instantiation of an object and so it comes under the category of creational design pattern. If we notice the name Factory method, that means there is a method which is a factory, and in general factories are involved with creational stuff and here with this an object is being created. It is one of the best ways to create an object where object creation logic is hidden to the client. Now Let’s look at the implementation.

Implementation:
1. Define a factory method inside an interface.
2. Let the subclass implements the above factory method and decide which object to create.

In Java constructors are not polymorphic, but by allowing subclass to create an object, we are adding polymorphic behavior to the instantiation. In short, we are trying to achieve Pseudo polymorphism by letting the subclass to decide what to create, and so this Factory method is also called as Virtual constructor. Let’s try to implement it with a real-time problem and some coding exercise.
Problem Statement :
Consider we want to implement a notification service through email, SMS, and push notification. Let’s try to implement this with the help of factory method design pattern. First we will design a UML class diagram for this.

In the above class diagram we have an interface called NotificationService, and three concrete classes are implementing NotificationService interface. A factory class NotificationFactory is created to get a NotificationService object. Let’s jump into the coding now.
Create Notification interface

filter_none

edit
close

play_arrow

link
brightness_4
code

public interface Notification {
    void notifyUser();
}

chevron_right


Note- Above interface could be created as an abstract class as well.
Create all implementation classes

SMSNotification.java
filter_none

edit
close

play_arrow

link
brightness_4
code

public class SMSNotification implements Notification {
  
    @Override
    public void notifyUser()
    {
        // TODO Auto-generated method stub
        System.out.println("Sending an SMS notification");
    }
}

chevron_right


EmailNotification.java
filter_none

edit
close

play_arrow

link
brightness_4
code

public class EmailNotification implements Notification {
  
    @Override
    public void notifyUser()
    {
        // TODO Auto-generated method stub
        System.out.println("Sending an e-mail notification");
    }
}

chevron_right


PushNotification.java
filter_none

edit
close

play_arrow

link
brightness_4
code

public class PushNotification implements Notification {
  
    @Override
    public void notifyUser()
    {
        // TODO Auto-generated method stub
        System.out.println("Sending a push notification");
    }
}

chevron_right


Create a factory class NotificationFactory.java to instantiate concrete class.



filter_none

edit
close

play_arrow

link
brightness_4
code

public class NotificationFactory {
    public Notification createNotification(String channel)
    {
        if (channel == null || channel.isEmpty())
            return null;
        if ("SMS".equals(channel)) {
            return new SMSNotification();
        }
        else if ("EMAIL".equals(channel)) {
            return new EmailNotification();
        }
        else if ("PUSH".equals(channel)) {
            return new PushNotification();
        }
        return null;
    }
}

chevron_right


Now let’s use factory class to create and get an object of concrete class by passing some information.

filter_none

edit
close

play_arrow

link
brightness_4
code

public class NotificationService {
    public static void main(String[] args)
    {
        NotificationFactory notificationFactory = new NotificationFactory();
        Notification notification = notificationFactory.createNotification("SMS");
        notification.notifyUser();
    }
}

chevron_right


Output : Sending an SMS notification


Real-time examples
This design pattern has been widely used in JDK, such as
1. getInstance() method of java.util.Calendar, NumberFormat, and ResourceBundle uses factory method design pattern.
2. All the wrapper classes like Integer, Boolean etc, in Java uses this pattern to evaluate the values using valueOf() method.
3. java.nio.charset.Charset.forName(), java.sql.DriverManager#getConnection(), java.net.URL.openConnection(), java.lang.Class.newInstance(), java.lang.Class.forName() are some of ther example where factory method design pattern has been used.

Conclusion
So far we learned what is Factory method design pattern and how to implement it. I believe now we have a fair understanding of the advantage of this design mechanism.

design-pattern-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.