Skip to main content
Dat 2. semester Bornholm
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Factory Pattern

Factory Pattern

Formål

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.


Problemet (uden 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);
    }
}

Problemer

  • Klassen kender alle konkrete klasser
  • Ny type kræver ændring i eksisterende kode
  • Bryder Open/Closed Principle

Løsningen: Factory Pattern

1. Fælles interface

public interface Notification {
    void send(String message);
}

2. Konkrete implementationer

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);
    }
}

3. Factory-klassen

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");
        };
    }
}

4. Brug Factory i service-klassen

public class NotificationService {

    public void notifyUser(String type, String message) {
        Notification notification =
                NotificationFactory.create(type);

        notification.send(message);
    }
}

Hvad har vi opnået?

  • NotificationService:
    • bruger ikke new
    • afhænger kun af interfacet
  • Objekt-oprettelse er samlet ét sted
  • Koden er lettere at udvide og vedligeholde

Kort opsummering

Factory Pattern handler om, hvem der opretter objekter – ikke hvad de gør.


Opgave

Design en PaymentFactory, der kan oprette:

  • CardPayment
  • MobilePayPayment
  • PayPalPayment

Brug kun interfacet Payment i din service-klasse.