Object creation logic scattered across client code means every new type requires editing multiple call sites. Factory centralizes creation, giving you one place to change when types change.
// ─── EXAMPLE 1 ──────────────────────────────────────────────────────────────
// WHAT WE ARE IMPLEMENTING:
// A notifications delivery framework routing alerts via Email, SMS, or Push
// channels.
//
// WHERE THE PATTERN FITS IN:
// NotificationFactory acts as the Creator. EmailNotificationFactory and
// SMSNotificationFactory represent Concrete Creators overriding the factory
// method to return matching product subclasses.
// ────────────────────────────────────────────────────────────────────────────
// --- Products ---
interface ParkingSpot {
String getId();
double getHourlyRate();
}
class CarSpot implements ParkingSpot {
private final String id;
public CarSpot(String id) { this.id = id; }
public String getId() { return id; }
public double getHourlyRate() { return 20.0; }
}
class BikeSpot implements ParkingSpot {
private final String id;
public BikeSpot(String id) { this.id = id; }
public String getId() { return id; }
public double getHourlyRate() { return 10.0; }
}
class TruckSpot implements ParkingSpot {
private final String id;
public TruckSpot(String id) { this.id = id; }
public String getId() { return id; }
public double getHourlyRate() { return 40.0; }
}
// --- Factory (centralized creation) ---
enum SpotType { CAR, BIKE, TRUCK }
class ParkingSpotFactory {
public static ParkingSpot createSpot(SpotType type, String id) {
return switch (type) {
case CAR -> new CarSpot(id);
case BIKE -> new BikeSpot(id);
case TRUCK -> new TruckSpot(id);
};
}
}
// --- Client code ---
public class Main {
public static void main(String[] args) {
ParkingSpot carSpot = ParkingSpotFactory.createSpot(SpotType.CAR, "A1");
ParkingSpot bikeSpot = ParkingSpotFactory.createSpot(SpotType.BIKE, "B2");
System.out.println("Car spot: " + carSpot.getId() + " Rate: " + carSpot.getHourlyRate());
System.out.println("Bike spot: " + bikeSpot.getId() + " Rate: " + bikeSpot.getHourlyRate());
}
}