Factory Design Pattern in Java: Definition, Structure, and Real-Life Examples
📘 Factory Design Pattern in Java
The Factory Design Pattern is a creational design pattern that provides an object-creation mechanism without exposing the creation logic to the end user.
Instead of creating objects directly using the new keyword, the factory class is responsible for object creation and returning the required object.
This pattern helps achieve loose coupling and better maintainability.
🧠 Core Idea of Factory Design Pattern
Create objects without exposing the instantiation logic to the client and refer to newly created objects using a common interface.
🧩 Three Main Logics in Factory Design Pattern
🔹 1. Implementation Logic
- Present in the subclasses
- Subclasses provide implementation of the interface methods
🔹 2. Object Creation Logic
- Present in the factory class
- The factory decides which object to create
🔹 3. Consumer / Utilization Logic
- The end user (client) accesses objects
- Objects are obtained only through the factory class
🛠️ Steps to Create Factory Design Pattern
✅ Step 1: Create an Interface
The interface contains abstract method(s).
public interface Vehicle {
void start();
}
✅ Step 2: Create Implementation Classes
Subclasses implement the interface and provide logic.
public class Car implements Vehicle {
public void start() {
System.out.println("Car started");
}
}
public class Bike implements Vehicle {
public void start() {
System.out.println("Bike started");
}
}
✅ Step 3: Create Factory Class
The factory class contains a static method that returns objects of implementation classes.
public class VehicleFactory {
public static Vehicle getVehicle(String type) {
if (type.equalsIgnoreCase("car")) {
return new Car();
} else if (type.equalsIgnoreCase("bike")) {
return new Bike();
}
return null;
}
}
✅ Step 4: Consumer Code
The client uses the factory to get objects.
Vehicle v = VehicleFactory.getVehicle("car");
v.start();
🌍 Real-Life Example
Think of a restaurant:
- You order food (client request)
- The kitchen (factory) prepares the dish
- You receive the food without knowing how it was cooked
⭐ Advantages of Factory Design Pattern
- Loose coupling between client and object creation
- Centralized object creation logic
- Easy to add new implementations
- Improves code maintainability
📌 When to Use Factory Pattern
- When object creation logic is complex
- When multiple implementations exist
- When client should not know the object creation details
Comments
Post a Comment