Level Up Your Java Skills!
Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!
SUBSCRIBE NOWWhat is the Factory Design Pattern?
The Factory Design Pattern is one of the most widely used creational patterns in Java. It defines an interface or abstract class for creating an object, but allows subclasses or factory methods to decide which specific class to instantiate.
By delegating object creation to a centralized factory, your application decouples client business logic from concrete implementation details, making your codebase significantly more flexible and maintainable.
Complete Java Code Implementation
Below is a clear, beginner-friendly example implementing the Factory Pattern with shapes:
// 1. Common Interface
interface Shape {
void draw();
}
// 2. Concrete Implementations
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle.");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Rectangle.");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square.");
}
}
// 3. Shape Factory
class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null || shapeType.trim().isEmpty()) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
// 4. Client / Driver Application
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape shape1 = factory.getShape("CIRCLE");
if (shape1 != null) {
shape1.draw();
}
Shape shape2 = factory.getShape("RECTANGLE");
if (shape2 != null) {
shape2.draw();
}
Shape shape3 = factory.getShape("SQUARE");
if (shape3 != null) {
shape3.draw();
}
}
}
Key Best Practices
- Code to Interfaces: The client program should interact exclusively through the interface type rather than concrete classes.
- Centralize Instantiation: Keep creation logic encapsulated inside factory methods so modifications do not impact client code.
- Support Extensibility: Introducing new implementations is seamless and only requires updating the factory logic.
Watch More Related Design Pattern Tutorials
Click here to watch in Youtube : https://www.youtube.com/watch?v=q9p-E19JFlA
| Factory Design Pattern - Implementation - Class Diagram |
Animal.java
public interface Animal
{
public String speak();
}
public class Dog implements Animal
{
@Override
public String speak()
{
return "Bark Bark Bark";
}
}
public class Duck implements Animal
{
@Override
public String speak()
{
return "Quack Quack Quack";
}
}