Factory patterns Flashcards
(4 cards)
What is creational design pattern?
Creational design patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.
List all Creational Design Patterns.
- Factory method
- Singleton
- Abstract method
- Builder
- Prototype
What are the main components of the Factory Method Pattern?
Product: Interface for the objects.
ConcreteProduct: Implements the product interface.
Creator: Declares the factory method.
ConcreteCreator: Implements the factory method and decides the object creation.
Factory method example
// Product Interface
interface Notification {
void send(String message);
}
// Concrete Product 1: Email Notification
class EmailNotification implements Notification {
@Override
public void send(String message) {
System.out.println(“Sending email with message: “ + message);
}
}
// Concrete Product 2: SMS Notification
class SMSNotification implements Notification {
@Override
public void send(String message) {
System.out.println(“Sending SMS with message: “ + message);
}
}
// Creator (Abstract)
abstract class NotificationFactory {
public abstract Notification createNotification(String notificationType);
}
// Concrete Creator
class ConcreteNotificationFactory extends NotificationFactory {
@Override
public Notification createNotification(String notificationType) {
if (“email”.equalsIgnoreCase(notificationType)) {
return new EmailNotification();
} else if (“sms”.equalsIgnoreCase(notificationType)) {
return new SMSNotification();
} else {
throw new IllegalArgumentException(“Unknown notification type”);
}
}
}
// Client Code
public class FactoryMethodExample {
public static void main(String[] args) {
// Creating the factory
NotificationFactory factory = new ConcreteNotificationFactory();
// Client doesn't need to know which class to instantiate Notification emailNotification = factory.createNotification("email"); emailNotification.send("Hello, this is your email!"); Notification smsNotification = factory.createNotification("sms"); smsNotification.send("Hello, this is your SMS!"); } }