Factory Pattern in Java: What It Is and How It Works
factory pattern in Java is a design pattern that creates objects without exposing the creation logic to the client. It provides a common interface to create different types of objects, letting subclasses decide which class to instantiate.How It Works
The factory pattern works like a factory in real life, where you go to a factory to get a product without knowing how it is made. In programming, instead of creating objects directly with new, you ask a factory class to create the object for you.
This means the client code does not need to know the details of how objects are created or which exact class is used. The factory handles this decision, making the code easier to manage and extend.
For example, if you want different types of shapes like circles or squares, the factory will decide which shape to create based on input, so your main code stays clean and simple.
Example
This example shows a simple factory that creates different Shape objects based on a given type.
interface Shape { void draw(); } 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"); } } 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; } } public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); Shape shape1 = shapeFactory.getShape("CIRCLE"); if (shape1 != null) { shape1.draw(); } Shape shape2 = shapeFactory.getShape("SQUARE"); if (shape2 != null) { shape2.draw(); } } }
When to Use
Use the factory pattern when your code needs to create objects but you want to keep the creation logic separate from the main code. This helps when you expect new types of objects to be added later without changing existing code.
It is useful in real-world cases like:
- Creating different types of user interface elements (buttons, text fields) depending on the platform.
- Generating different database connections depending on configuration.
- Building games where different characters or enemies are created dynamically.
This pattern improves code flexibility, readability, and maintenance.
Key Points
- The factory pattern hides object creation details from the client.
- It uses a common interface to create different types of objects.
- It helps in managing and extending code easily.
- It promotes loose coupling between client and object creation.