Creational design patterns:

Builder Pattern 

The Builder Pattern is a creational design pattern in software engineering used to construct complex objects step by step. Instead of creating a large constructor with many parameters (which can get confusing), the Builder pattern allows you to build an object incrementally, making the construction process more readable, flexible, and maintainable.

Key Components

  1. Builder – Defines the abstract interface for creating parts of a Product.

  2. ConcreteBuilder – Implements the Builder interface and constructs parts of the Product. It also keeps track of the representation it creates.

  3. Director (optional) – Controls the construction process using a Builder object.

  4. Product – The complex object being built.

Modern Usage in Java (Fluent Builder without Director)

class User { private String firstName; private String lastName; private int age; private User(UserBuilder builder) { this.firstName = builder.firstName; this.lastName = builder.lastName; this.age = builder.age; } public static class UserBuilder { private String firstName; private String lastName; private int age; public UserBuilder setFirstName(String firstName) { this.firstName = firstName; return this; } public UserBuilder setLastName(String lastName) { this.lastName = lastName; return this; } public UserBuilder setAge(int age) { this.age = age; return this; } public User build() { return new User(this); } } @Override public String toString() { return firstName + " " + lastName + ", Age: " + age; } } // Usage User user = new User.UserBuilder() .setFirstName("John") .setLastName("Doe") .setAge(30) .build(); System.out.println(user);

Output:

John Doe, Age: 30

Prototype Pattern


The Prototype Pattern is a creational design pattern used to create new objects by cloning existing ones instead of creating them from scratch.
It is useful when object creation is costly or complex, and you want to replicate objects efficiently.

Example in Java

// Prototype interface interface Prototype { Prototype clone(); } // Concrete Prototype class Employee implements Prototype { private String name; private String department; public Employee(String name, String department) { this.name = name; this.department = department; } @Override public Prototype clone() { return new Employee(this.name, this.department); } @Override public String toString() { return "Employee{name='" + name + "', department='" + department + "'}"; } } // Client public class Main { public static void main(String[] args) { Employee original = new Employee("John Doe", "IT"); // Clone Employee cloned = (Employee) original.clone(); System.out.println(original); System.out.println(cloned); } }

Output:

Employee{name='John Doe', department='IT'} Employee{name='John Doe', department='IT'}

Comments

Popular posts from this blog

Archunit test

Hexagonal Architecture

visitor design pattern