Factory patterns Flashcards

(4 cards)

1
Q

What is creational design pattern?

A

Creational design patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

List all Creational Design Patterns.

A
  • Factory method
  • Singleton
  • Abstract method
  • Builder
  • Prototype
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the main components of the Factory Method Pattern?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Factory method example

A

// 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!");
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly