Sitemap

Member-only story

Factory Pattern Using Java 8 Lambda Expressions — Best Practice

Explore the Factory Design Pattern and its implementation using Java 8 Lambda expressions

3 min readFeb 24, 2025

Introduction

In this article, we will explore the Factory Design Pattern and its implementation using Java 8 Lambda expressions. The Factory Pattern falls under the Creational Design Pattern category, providing a structured way to instantiate objects dynamically.

Definition of Factory Design Pattern

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.” — Head First Design Patterns

We will first implement the Factory Pattern without lambda expressions, then see how we can simplify it using Java 8 Lambda Expressions and Method References.

Factory Design Pattern: Traditional Implementation (Without Lambda Expressions)

Factory Design Pattern

Step 1: Create an Interface (Shape.java)

public interface Shape {
void draw();
}

Step 2: Implement Concrete Shape Classes

Rectangle.java

public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}

Square.java

public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}

Circle.java

public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}

Step 3: Define an Enum for Shape Types (ShapeType.java)

public enum ShapeType {
CIRCLE, RECTANGLE, SQUARE;
}

Step 4: Implement the Factory Class (ShapeFactory.java)

--

--

No responses yet