CodexBloom - Programming Q&A Platform

Unexpected behavior when using Composition with Factory Pattern in Java

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-07
java oop design-patterns factory-pattern

I'm trying to debug I'm sure I'm missing something obvious here, but I've been trying to implement a simple Factory Pattern in my Java application to create different types of vehicles, specifically focusing on adding new vehicle types without modifying existing code. However, I’m facing unexpected behavior when trying to use composition instead of inheritance. Here's my current implementation: ```java interface Vehicle { void drive(); } class Car implements Vehicle { public void drive() { System.out.println("Driving a car!"); } } class Bike implements Vehicle { public void drive() { System.out.println("Riding a bike!"); } } class VehicleFactory { public static Vehicle createVehicle(String type) { switch (type.toLowerCase()) { case "car": return new Car(); case "bike": return new Bike(); default: throw new IllegalArgumentException("Unknown vehicle type: " + type); } } } class VehicleService { private Vehicle vehicle; public VehicleService(Vehicle vehicle) { this.vehicle = vehicle; } public void startDriving() { vehicle.drive(); } } public class Main { public static void main(String[] args) { Vehicle vehicle = VehicleFactory.createVehicle("car"); VehicleService service = new VehicleService(vehicle); service.startDriving(); vehicle = VehicleFactory.createVehicle("bike"); service = new VehicleService(vehicle); service.startDriving(); } } ``` When I run this code, the output is as expected, showing that I can create and use both a `Car` and a `Bike`. However, I’ve noticed that if I try to add a new vehicle type, say a `Truck`, I have to modify the `VehicleFactory` class, which goes against the Open/Closed Principle. I thought of separating the creation of vehicle types into their own classes using composition, like this: ```java class Truck implements Vehicle { public void drive() { System.out.println("Driving a truck!"); } } class TruckFactory { public Vehicle createTruck() { return new Truck(); } } ``` However, now I have to create a new factory class for each vehicle type, which seems inefficient. I’m looking for a way to use composition effectively while adhering to OOP principles. What am I missing? Is there a design pattern that better suits my needs? Additionally, I’m facing issues with code maintainability and scalability as I am constantly adding new vehicle types. I’d appreciate any suggestions or examples on how to refactor this correctly. I'm using Java 17 and aiming for clean, maintainable code following best practices. Thanks! My development environment is macOS. I'd really appreciate any guidance on this. Thanks for your help in advance!