The Factory Design Pattern is used to create objects without specifying their exact class.
Instead of using new
, you delegate object creation to a factory method that returns the right object based on some input.
Look out for these clues in the code:
- You see object creation like:
SomeType obj = FactoryClass.getObject("type");
- There's an interface or abstract base class being used as the reference type.
- Concrete classes are hidden from the main logic.
- Object creation is controlled in one central place (the factory).
- You have a common interface or superclass with many implementations.
- Object creation logic may change or is complex.
- You want to decouple object creation from usage.
- You want to easily extend the system by adding new object types.
Create an interface or abstract class that defines what the object should be able to do.
Create multiple classes that implement this interface differently.
Write a class that takes input and returns the appropriate implementation.
Instead of creating the entity first, write a factory method in driver class.
E.g: EntityInterface entity = EntityFactoryBuilder.getEntity(entityType);
In EntityFactoryBuilder, create a method getEntity() that will take entityType and return entity of that class. Remember to make it generic.
E.g: Entity getEntity(String entityType){ Entity entity = new EntityType(); return entity; }
In Entity interface write the behaviour and in EntityType which implements Entity define this behaviour.
E.g class EntityType implements Entity{ void behaviour(){} }
- Encapsulation: Hides object creation logic.
- Flexibility: Easily switch or add implementations.
- Decoupling: Main logic doesn’t depend on concrete classes.
- Clean Code: Centralized creation logic.
API Class | Factory Method | Internally Returns |
---|---|---|
Calendar |
getInstance() |
GregorianCalendar |
NumberFormat |
getInstance() |
Locale Formatter |
DriverManager |
getConnection() |
MySQL/Oracle Driver |
ResourceBundle |
getBundle() |
Locale Bundle |
- Factory class names:
TypeFactory
,ObjectCreator
, etc. - Factory methods:
create()
,getInstance()
,build()
,getType(type)
.
Factory Pattern is like a smart assistant.
You just say what you want, and it knows how to get the right object for you — without telling you the details.
Made with ❤️ by syedyshiraz