Factory Pattern
Factory Pattern bruges til at adskille oprettelsen af objekter fra brugen af dem.
I stedet for at bruge new direkte i forretningslogikken, flyttes ansvaret for at oprette objekter til en Factory.
class NotificationService {
public void notifyUser(String type, String message) {
Notification notification;
if (type.equals("email")) {
notification = new EmailNotification();
} else if (type.equals("sms")) {
notification = new SmsNotification();
} else {
throw new IllegalArgumentException("Unknown type");
}
notification.send(message);
}
}
- Klassen kender alle konkrete klasser
- Ny type kræver ændring i eksisterende kode
- Bryder Open/Closed Principle
public interface Notification {
void send(String message);
}
public class EmailNotification implements Notification {
public void send(String message) {
System.out.println("Email: " + message);
}
}
public class SmsNotification implements Notification {
public void send(String message) {
System.out.println("SMS: " + message);
}
}
public class NotificationFactory {
public static Notification create(String type) {
return switch (type) {
case "email" -> new EmailNotification();
case "sms" -> new SmsNotification();
default -> throw new IllegalArgumentException("Unknown type");
};
}
}
public class NotificationService {
public void notifyUser(String type, String message) {
Notification notification =
NotificationFactory.create(type);
notification.send(message);
}
}
NotificationService:- bruger ikke
new - afhænger kun af interfacet
- bruger ikke
- Objekt-oprettelse er samlet ét sted
- Koden er lettere at udvide og vedligeholde
Factory Pattern handler om, hvem der opretter objekter – ikke hvad de gør.
Design en PaymentFactory, der kan oprette:
CardPaymentMobilePayPaymentPayPalPayment
Brug kun interfacet Payment i din service-klasse.