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");
}
}
Comments
Join the discussionNo comments yet. Be the first to comment.
Design Pattern
This is a design pattern series. Where you can find important object oriented patterns that helps you to write better maintainable and clean code


