DEV Community
π Why This Blog?
When I first came across the Factory Design Pattern, it felt like magic. But with a bit of practical exploration, I realized itβs just a smart way to decouple object creation from usage.
This devblog is my attempt to help you understand the Factory Pattern the way I wish someone explained it to me.
π What is the Factory Pattern?
The Factory Pattern provides a way to delegate the instantiation logic to a separate method or class. Instead of using new
in multiple places, we delegate it to a Factory
that knows how to create different objects based on some input.
In simple terms: You say what you want, not how to create it.
π Spotting a Factory Pattern
You might be looking at a Factory Pattern if you see:
- Code like:
IEnemy enemy = EnemyFactory.getEnemy("orc");
- One interface or abstract class, but many concrete implementations.
- A centralized class responsible for returning the appropriate implementation.
π§ͺ Code Example β Enemy Factory
Step 1: Create an interface
public interface IEnemy {
void attack();
}
Step 2: Implement the interface in multiple classes
public class Orc implements IEnemy {
public void attack() {
System.out.println("Orc attacks with axe!");
}
}
public class Goblin implements IEnemy {
public void attack() {
System.out.println("Goblin throws dagger!");
}
}
Step 3: Create the Factory Class
public class EnemyFactory {
public static IEnemy getEnemy(String enemyType) {
if (enemyType.equalsIgnoreCase("orc")) {
return new Orc();
} else if (enemyType.equalsIgnoreCase("goblin")) {
return new Goblin();
}
throw new IllegalArgumentException("Unknown enemy type");
}
}
Step 4: Use it in your code
public class Game {
public static void main(String[] args) {
IEnemy enemy1 = EnemyFactory.getEnemy("orc");
enemy1.attack();
IEnemy enemy2 = EnemyFactory.getEnemy("goblin");
enemy2.attack();
}
}
π§ Personal Notes to Apply Factory Pattern
Start with usage:
IEnemy enemy = EnemyFactory.getEnemy("orc");
Then build everything around it:
- Create
IEnemy
interface - Create
Orc
,Goblin
, etc. classes that implementIEnemy
- Create
EnemyFactory
to returnIEnemy
objects
Keep the logic of what to return in one place β the factory.
β Benefits
- Centralized object creation logic
- Clean, readable code
- Easy to add new object types
- Loose coupling between client and concrete classes
π More Examples
Check out more hands-on examples of the Factory Pattern here:
π Factory Design Pattern on GitHub
π§΅ TL;DR
Factory Pattern is a smart way to delegate object creation.
You donβt worry aboutnew
β just ask the factory for what you need.
Made with β€οΈ by syedyshiraz
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)