Factory Method Pattern Example

๐Ÿญ Factory Method Pattern in Java — Step-by-Step Guide

The Factory Method Pattern is one of the key Creational Design Patterns in Java.
It provides an interface for creating objects, allowing subclasses or factory logic to decide which class to instantiate at runtime.

Rather than creating objects using the new keyword directly, the Factory hides the instantiation logic inside a dedicated class — improving flexibility, maintainability, and decoupling.


๐ŸŽฏ Real-World Analogy

Think of a person registration system.
Based on user input (M or F), we want to create a Male or Female object.

Instead of writing:

Person p = new Male();

everywhere in the code, we delegate that logic to a Factory.
So the client simply calls:

Person p = PersonFactory.getPerson("M");

and the factory takes care of the rest.


⚙️ Pattern Intent

  • Define an interface for object creation.

  • Let subclasses or logic decide which concrete class to instantiate.

  • Decouple object creation from object usage.


๐Ÿงฉ Step 1: Create an Interface (Person.java)

package com.vinod.design.factory; /** * Common interface for all Person types. */ public interface Person { void say(); }

๐Ÿงฉ Step 2: Create Concrete Implementations

๐Ÿ‘จ Male.java

package com.vinod.design.factory; public class Male implements Person { @Override public void say() { System.out.println("I am male"); } }

๐Ÿ‘ฉ Female.java

package com.vinod.design.factory; public class Female implements Person { @Override public void say() { System.out.println("I am female"); } }

๐Ÿงฉ Step 3: Create the Factory Class

package com.vinod.design.factory; /** * Factory class that decides which Person object to create. */ public class PersonFactory { /** * Creates and returns a Person instance based on the input gender. * * @param gender "M" for Male, "F" for Female * @return Person instance or null if input is invalid */ public Person getPerson(String gender) { if (gender == null) { return null; } if (gender.equalsIgnoreCase("M")) { return new Male(); } else if (gender.equalsIgnoreCase("F")) { return new Female(); } return null; // can also throw IllegalArgumentException } }

๐Ÿงฉ Step 4: Test the Factory

package com.vinod.design.factory; public class FactoryTest { public static void main(String[] args) { PersonFactory factory = new PersonFactory(); // Create Male instance Person p1 = factory.getPerson("M"); p1.say(); // Create Female instance Person p2 = factory.getPerson("F"); p2.say(); // Invalid input test Person p3 = factory.getPerson("X"); if (p3 == null) { System.out.println("Invalid gender input. No object created."); } } }

๐Ÿงพ Output

I am male I am female Invalid gender input. No object created.

๐Ÿง  How It Works (Step-by-Step)

StepActionDescription
1️⃣Client requests object creationCalls factory.getPerson("M")
2️⃣Factory checks inputEvaluates input value (“M” / “F”)
3️⃣Factory creates instanceUses new Male() or new Female()
4️⃣Factory returns resultReturns Person reference to caller
5️⃣Client uses interfaceCalls say() without knowing the concrete type

๐Ÿ” Advantages of Factory Method Pattern

BenefitDescription
✅ EncapsulationObject creation logic hidden from client
✅ Loose CouplingClient depends only on interface, not implementation
✅ ExtensibilityNew types can be added without changing client code
✅ ReusabilityCommon creation logic centralized in the factory
✅ SimplicityCleaner and more readable code

⚠️ When to Use Factory Method

  • When you don’t know the exact type of object to create at compile time.

  • When you want to isolate the creation logic.

  • When the object creation process is complex or conditional.

  • When you want to return subclasses or implementations dynamically.


๐Ÿงฉ UML-Like Text Diagram

+-------------------+ | Person | <-- Interface |-------------------| | + say() | +---------+---------+ | +------------+------------+ | | +-------------+ +-------------+ | Male | | Female | |-------------| |-------------| | + say() | | + say() | +-------------+ +-------------+ ^ | +----------------+ | PersonFactory | |----------------| | + getPerson() | +----------------+ ^ | +----------------+ | FactoryTest | +----------------+

๐Ÿงญ Real-World Examples in Java

Use CaseDescription
Calendar.getInstance()Returns different Calendar subclasses based on locale/timezone
NumberFormat.getInstance()Returns appropriate number format (e.g., for locale)
JDBC DriverManager.getConnection()Creates a connection for a given database type
ExecutorService.newFixedThreadPool()Factory method returning different thread pool types

✅ Summary

ConceptDescription
Pattern TypeCreational
PurposeDelegate object creation to a factory
Core ComponentsInterface, Concrete Classes, Factory Class
Key BenefitEncapsulates creation logic, enhances flexibility
Real ExamplePersonFactory creating Male or Female objects

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts