Factory Design Pattern

Loading...
By technoayan
Design-PatternFactory
Factory Design Pattern
0 min read
LLD
Design-Pattern
Factory

Factory Design Pattern

Understand the Factory Design Pattern in Java with real-life analogies, clean code examples, and best practices. Learn how it promotes loose coupling and simplifies object creation.

🏭 Factory Design Pattern in Java

The Factory Design Pattern is a creational design pattern used to create objects without exposing the creation logic to the client.

Instead of using new keyword directly, we delegate the object creation to a factory method.


🎯 Real-Life Analogy

πŸ§ƒ Imagine ordering a drink at a juice shop.

You don't care how the juice is made – you just say "Give me an Orange Juice", and the shop handles the rest.

Similarly, with the Factory Pattern, the factory class creates the object based on your input.


πŸ”§ When to Use It?

  • When the object creation logic is complex or depends on conditions.
  • When you want to centralize creation logic.
  • When you need loose coupling between classes.

πŸ”₯ Basic Example – Shape Factory

πŸ”Έ Step 1: Create a common interface

β˜•JAVA
interface Shape {
    void draw();
}

πŸ”Έ Step 2: Implement different shapes

β˜•JAVA
class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

class Square implements Shape {
    public void draw() {
        System.out.println("Drawing a Square");
    }
}

πŸ”Έ Step 3: Create a Factory class

β˜•JAVA
class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null) return null;

        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }

        return null;
    }
}

πŸ”Έ Step 4: Use Factory in Main Class

β˜•JAVA
public class Main {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();

        Shape shape1 = factory.getShape("CIRCLE");
        shape1.draw();

        Shape shape2 = factory.getShape("SQUARE");
        shape2.draw();
    }
}

βœ… Output

Drawing a Circle Drawing a Square

πŸ“Œ Key Concepts

| Concept | Description | | --------------------- | ------------------------------------------------- | | Loose Coupling | Client doesn’t care how objects are created | | Reusability | Easy to manage and extend object creation | | Encapsulation | Hides object instantiation logic | | Open/Closed Principle | Easy to add new shapes without modifying old code |


🧠 Real-World Use Case: Notification Service

Suppose your app supports notifications via Email and SMS. The client should just say β€œSend Notification” β€” the factory decides how.


πŸ”Έ Step 1: Notification Interface

β˜•JAVA
interface Notification {
    void notifyUser();
}

πŸ”Έ Step 2: Implementations

β˜•JAVA
class EmailNotification implements Notification {
    public void notifyUser() {
        System.out.println("Sending Email Notification");
    }
}

class SMSNotification implements Notification {
    public void notifyUser() {
        System.out.println("Sending SMS Notification");
    }
}

πŸ”Έ Step 3: Factory Class

β˜•JAVA
class NotificationFactory {
    public Notification createNotification(String type) {
        if (type == null || type.isEmpty()) return null;

        if (type.equalsIgnoreCase("EMAIL")) {
            return new EmailNotification();
        } else if (type.equalsIgnoreCase("SMS")) {
            return new SMSNotification();
        }

        return null;
    }
}

πŸ”Έ Step 4: Main Class

β˜•JAVA
public class NotificationService {
    public static void main(String[] args) {
        NotificationFactory factory = new NotificationFactory();

        Notification email = factory.createNotification("EMAIL");
        email.notifyUser();

        Notification sms = factory.createNotification("SMS");
        sms.notifyUser();
    }
}

βœ… Output

Sending Email Notification Sending SMS Notification

🚫 Anti-Patterns to Avoid

  • ❌ Huge if-else chains in factory β†’ use enum or config to clean it later.
  • ❌ Mixing business logic inside factory β†’ keep factory focused on object creation only.

🧠 Interview Q&A

Q: What pattern category does Factory belong to? A: Creational

Q: What's the difference between Factory and Abstract Factory? A:

  • Factory β†’ returns one family/type of object.
  • Abstract Factory β†’ returns related objects from multiple factories.

Q: Why not just use new? A: Because new tightly couples the client with the implementation. Factory gives you flexibility and control.


πŸ“š Summary

  • βœ… Factory Pattern helps in creating objects in a clean and controlled way.
  • 🧱 Promotes loose coupling, reusability, and maintainability.
  • πŸ“¦ Useful when object creation is conditional, dynamic, or complex.

Thanks for reading!

technoayan

Author & Tech Enthusiast

"Keep learning, keep growing, and keep sharing knowledge with the world."

Rate This Post

Share your thoughts and help others discover great content

Sign in to rate this post and share your feedback

Community Rating

No ratings yet. Be the first to rate this post!

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!

TechnoBlogs

by Ayan Ahmad

Exploring the world of technology through insightful articles, tutorials, and personal experiences. Join me on this journey of continuous learning and innovation.

Stay Updated

Built With

React
Next.js
Tailwind
Firebase
Powered by Coffee

Every line of code written with love and caffeine β˜•

Β© 2025 TechnoBlogsβ€’Made withbyAyan Ahmad

Open source β€’ Privacy focused β€’ Built for developersβ€’Privacy Policyβ€’Terms of Service