Search code examples
javafactory-pattern

Factory Pattern: How to access properties of concrete product classes from client?


I'm considering using Factory Pattern for creation of objects in a web application, but what I fail to grasp is how do I access the properties of these objects.

Simplified Example: I have a CarFactory Interface, implemented by two concrete classes TruckCarFactory and PickupCarFactory, also a Car Interface implemented by concrete Pickup and Truck classes. Now when creating a new Truck my client speaks to the CarFactory Interface creating a new Car.

Truck objects however are supposed to have lots of properties, which I usually would have as private members with getters/setters in the Truck class.

How do I best access these properties from my client code? Should I really put all getters/setters into the CarFactory Interface? If so, this would imply that Trck and Pickup object must have identical set of properties?


Solution

  • Getters and setters should be in the Car interface, and yes... best practice-wise Truck and Pickup should have the same set of properties. They could have additional properties outside of the car implementation but the thing that pulls out a pickup/truck from the factory should be agnostic of those.