Sure! Here’s an example of the Factory Pattern in Java. The Factory Pattern is a creational design pattern that provides an interface for creating objects, but allows subclasses to alter the type of objects that will be created.
Scenario:
Let’s create a system for a logistics company where different types of vehicles (e.g., Truck, Ship) can be used for transportation. We’ll use the Factory Pattern to create these vehicle objects.
Components:
- Product Interface: Declares the interface for objects that the factory method creates.
- Concrete Product Classes: Implement the
Productinterface. - Creator (Factory) Interface: Declares the factory method.
- Concrete Creator (Factory) Classes: Implement the factory method to create specific products.
Explanation:
- Product Interface: The
Transportinterface declares thedelivermethod. - Concrete Product Classes: The
TruckandShipclasses implement theTransportinterface and provide specific implementations of thedelivermethod. - Creator (Factory) Interface: The
Logisticsabstract class declares the factory methodcreateTransportand a methodplanDeliverythat uses the product created by the factory method. - Concrete Creator (Factory) Classes: The
RoadLogisticsandSeaLogisticsclasses implement the factory methodcreateTransportto create specific products (TruckandShiprespectively). - Client Class: The
Clientclass uses the factory classes to create and use products.
Advantages of Factory Pattern:
- Encapsulation: The Factory Pattern encapsulates the object creation process, hiding it from the client.
- Decoupling: It decouples the client code from the object creation code, making the system more flexible and easier to extend.
- Single Responsibility Principle: It adheres to the Single Responsibility Principle by delegating the responsibility of object creation to specific factory classes.
- Open/Closed Principle: The system can be extended with new product types without modifying existing code, adhering to the Open/Closed Principle.

