Design patterns

suggest change

Design patterns are standard, reusable solutions to common software design problems. In Java, patterns are categorized into three main families: Creational, Structural, and Behavioral.

Creational Patterns

Creational patterns deal with object creation mechanisms, decoupling object instantiation from the classes using them.

Builder Pattern

The Builder pattern avoids cumbersome "telescoping constructors" and allows constructing complex immutable objects step by step:

public class User {
    private final String firstName;
    private final String lastName;
    private final String email;
    private final int age;

    private User(Builder builder) {
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.email = builder.email;
        this.age = builder.age;
    }

    public static class Builder {
        private final String firstName;
        private final String lastName;
        private String email = "";
        private int age = 0;

        public Builder(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public Builder email(String email) {
            this.email = email;
            return this;
        }

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }

    public static void main(String[] args) {
        User user = new User.Builder("John", "Doe")
                .email("john.doe@example.com")
                .age(30)
                .build();
        System.out.println("Created user: " + user.firstName + " " + user.lastName);
    }
}

Factory Method Pattern

Defines an interface for creating objects while letting subclasses decide which concrete class to instantiate:

interface Notification {
    void notifyUser();
}

class EmailNotification implements Notification {
    public void notifyUser() {
        System.out.println("Sending an email notification");
    }
}

class SMSNotification implements Notification {
    public void notifyUser() {
        System.out.println("Sending an SMS notification");
    }
}

class NotificationFactory {
    public static Notification createNotification(String channel) {
        return switch (channel.toUpperCase()) {
            case "SMS" -> new SMSNotification();
            case "EMAIL" -> new EmailNotification();
            default -> throw new IllegalArgumentException("Unknown channel: " + channel);
        };
    }
}

Structural Patterns

Structural patterns ease design by identifying a simple way to realize relationships among entities.

Adapter Pattern

Converts the interface of a class into another interface expected by clients:

interface MediaPlayer {
    void play(String filename);
}

class AdvancedAudioPlayer {
    public void playMp4(String filename) {
        System.out.println("Playing MP4 file: " + filename);
    }
}

class AudioAdapter implements MediaPlayer {
    private final AdvancedAudioPlayer advancedPlayer;

    public AudioAdapter(AdvancedAudioPlayer advancedPlayer) {
        this.advancedPlayer = advancedPlayer;
    }

    @Override
    public void play(String filename) {
        advancedPlayer.playMp4(filename);
    }
}

Decorator Pattern

Attaches additional responsibilities to an object dynamically. Java's java.io stream classes are a prime example:

import java.io.*;

// The Decorator pattern wraps streams to add buffering and data parsing:
BufferedReader reader = new BufferedReader(
    new InputStreamReader(new FileInputStream("data.txt"))
);

Behavioral Patterns

Behavioral patterns characterize how classes or objects interact and distribute responsibility.

Strategy Pattern with Lambdas

The Strategy pattern defines a family of algorithms and encapsulates each one. In modern Java, functional interfaces and lambdas make strategy implementation concise:

import java.util.List;
import java.util.function.Predicate;

public class FilterService {
    public static <T> List<T> filter(List<T> list, Predicate<T> strategy) {
        return list.stream().filter(strategy).toList();
    }

    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);

        // Different filtering strategies supplied as lambdas
        List<Integer> evens = filter(numbers, n -> n % 2 == 0);
        List<Integer> greaterThanThree = filter(numbers, n -> n > 3);

        System.out.println("Evens: " + evens);
        System.out.println("Greater than 3: " + greaterThanThree);
    }
}

Observer Pattern

Defines a one-to-many dependency so that when one object changes state, all its dependents are notified automatically:

import java.util.ArrayList;
import java.util.List;

interface EventListener {
    void onEvent(String event);
}

class EventManager {
    private final List<EventListener> listeners = new ArrayList<>();

    public void subscribe(EventListener listener) {
        listeners.add(listener);
    }

    public void notify(String event) {
        for (EventListener listener : listeners) {
            listener.onEvent(event);
        }
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents