Tuesday, February 25, 2025

Java Creational Factory

📁 File Structure

/FactoryMethodPattern
│── Product.java
│── ConcreteProductA.java
│── ConcreteProductB.java
│── Creator.java
│── ConcreteCreatorA.java
│── ConcreteCreatorB.java
│── Main.java
    

1. Product.java (Abstract Product Interface)

// Abstract Product interface
public interface Product {
    void use();
}
    

2. ConcreteProductA.java & ConcreteProductB.java (Concrete Products)

ConcreteProductA.java

// Concrete Product A
public class ConcreteProductA implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProductA");
    }
}
    

ConcreteProductB.java

// Concrete Product B
public class ConcreteProductB implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProductB");
    }
}
    

3. Creator.java (Abstract Factory Class)

// Abstract Creator class
public abstract class Creator {
    // Factory Method: Must be implemented by concrete creators
    public abstract Product factoryMethod();
}
    

4. ConcreteCreatorA.java & ConcreteCreatorB.java (Factory Implementations)

ConcreteCreatorA.java

// Concrete Creator A
public class ConcreteCreatorA extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductA();
    }
}
    

ConcreteCreatorB.java

// Concrete Creator B
public class ConcreteCreatorB extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductB();
    }
}
    

5. Main.java (Client Code)

public class Main {
    public static void main(String[] args) {
        // Create a factory for ProductA
        Creator creatorA = new ConcreteCreatorA();
        Product productA = creatorA.factoryMethod();
        productA.use(); // Output: Using ConcreteProductA

        // Create a factory for ProductB
        Creator creatorB = new ConcreteCreatorB();
        Product productB = creatorB.factoryMethod();
        productB.use(); // Output: Using ConcreteProductB
    }
}
    

🎯 Key Takeaways

  • Encapsulation: The client does not know which concrete product it gets.
  • Scalability: Easily add new products and factories.
  • Decoupling: The factory method isolates the creation logic.

No comments:

Abstract Factory Pattern in C#

Below is a C# implementation of the Abstract Factory design pattern, a Creational pattern, following the Gang of Four (GoF) structure....