Loading
factory-method

Factory Method in Java

  • It is a creational design pattern that talks about the creation of an object. The factory design pattern says to define an interface ( A java interface or an abstract class) for creating an object and let the subclasses decide which class to instantiate. 
  • It is one of the best ways to create an object where object creation logic is hidden from the client. Now Let’s look at the implementation.

Implementation:

  • Define a factory method inside an interface. 
  • The subclass must (obey the ‘contract of abstract’  otherwise, the class must be declared as Abstract) Implement 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 add polymorphic behaviour to the instantiation. 
  • Let us implement it with a real-time problem and some coding exercises.

Example:

Notification.java

package com.factorymethod;

public interface Notification {  //Interface
	void notifyUser();
}

SmsNotification.java

package com.factorymethod;

public class SmsNotification implements Notification{
	public void notifyUser() {
		System.out.println("Sending an SMS notification!!");
	}
}

EmailNotification.java

package com.factorymethod;

public class EmailNotification implements Notification{
	public void notifyUser() {
		System.out.println("Sending an e-mail notification!!");
	}
}

PushNotification.java

package com.factorymethod;

public class PushNotification implements Notification{
	public void notifyUser() {
		System.out.println("Sending a push notification!!");
	}
}

NotificationFactory.java

package com.factorymethod;

public class NotificatioFacory {
	public Notification createNotification(String channel) {
		if(channel==null || channel.isEmpty()) {
			return null;
		}
		switch (channel) {
		case "SMS": 
			return new SmsNotification();
		case "EMAIL": 
			return new EmailNotification();
		case "PUSH": 
			return new PushNotification();

		default: 
			throw new IllegalArgumentException("Unknown channel"+channel);
		}
	}
}

NotificationService.java

package com.factorymethod;

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

Output:

Sending an SMS notification!!