Skip to main content

Factory Method

Updated 2 min readMarkdown
Part of seriesDesign Pattern

In the Factory Design Pattern, a factory class takes input from the user and returns an object based on that input. This approach often requires numerous if, else if, and else statements; adding a new class necessitates the addition of yet another else if block. The Factory Method pattern addresses this issue by delegating the object creation process from a method in the superclass to its subclasses.

Core Concept: Instead of returning multiple types of objects through a single superclass, a separate factory class is created for each class. An interface is used to define the factory method, while the actual implementation is handled by the child classes.

Notification Interface

public interface Notification {

    public void send(String message);

}

Email Notification Class

public class EmailNotification implements Notification{


    @Override
    public void send(String message) {

        System.out.println("Message sent via email");

    }
}

Push Notification Class

public class PushNotification implements Notification{


    @Override
    public void send(String message) {

        System.out.println("Message sent via push system");

    }
}

Main Factory Interface

public interface NotificationFactory {

    public Notification create();

}

Email Notification Factory Class

public class EmailNotificationFactory {

    public Notification create() {

        return new EmailNotification();
    }

}

Push Notification Factory Class

public class PushNotificationFactory {

    public Notification create() {

        return new PushNotification();
    }

}

Let's Test

public class TestNotification {

    public static void main(String[] args){

        NotificationFactory factory = new EmailNotificationFactory ();

        Notification email = factory.create();

        email.send("Hello");
    
    
    }

}

2 views

No comments yet. Be the first to comment.

Design Pattern

Part 3 of 4

This is a design pattern series. Where you can find important object oriented patterns that helps you to write better maintainable and clean code

Up nextThe FactorySuppose you want to add a payment feature to your e-commerce website. You have multiple payment gateways, such as bKash and Nagad. A user selects a payment gateway from the front end and submits the p

More from this blog