Introduction to Java Design Patterns

Tutorial 1 of 5

Introduction to Java Design Patterns


1. Introduction

Brief Explanation of the Tutorial's Goal

This tutorial aims to introduce you to design patterns, an advanced concept in Java programming. Design patterns are standard solutions to common problems in software design. They are like templates you can mold to suit your own needs.

What You Will Learn

By the end of this tutorial, you will:
- Understand what design patterns are
- Know the types of design patterns and their uses
- Be able to apply design patterns in Java programming

Prerequisites

This tutorial assumes you have a basic understanding of Java programming including classes, objects, inheritance, and interfaces. Familiarity with concepts like data structures and algorithms will be useful but not mandatory.


2. Step-by-Step Guide

Explanation of Concepts

Design patterns are divided into three types: Creational, Structural, and Behavioral.

  1. Creational Patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

  2. Structural Patterns concern class and object composition. They provide a way to ensure that different parts of a system work together in a structured and manageable way.

  3. Behavioral Patterns are about identifying common communication patterns between objects and realize these patterns.

Examples with Comments and Best Practices

  1. Singleton Pattern (Creational): Ensures that only one instance of a class is created.
public class Singleton {
    // Create a private static instance of the class
    private static Singleton instance = null;

    // Make the constructor private so it's not accessible outside
    private Singleton() {}

    // Provide a global point of access to the instance
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Tip: Use Singleton when you want to eliminate the option of instantiating more than one object.

  1. Adapter Pattern (Structural): Allows two incompatible interfaces to work together.
// Existing Interface
public interface Temperature {
    double getTemperature();
}

// New Interface
public interface TemperatureInFahrenheit {
    double getTemperatureInFahrenheit();
}

// Adapter Class
public class TemperatureAdapter implements TemperatureInFahrenheit {
    Temperature temp;

    public TemperatureAdapter(Temperature temp) {
        this.temp = temp;
    }

    public double getTemperatureInFahrenheit() {
        return convertCelsiusToFahrenheit(temp.getTemperature());
    }

    private double convertCelsiusToFahrenheit(double celsius) {
        return ((celsius * 9 / 5) + 32);
    }
}

Tip: Use Adapter Pattern when you want to use an existing class and its interface is not compatible with the rest of your code.


3. Code Examples

  1. Observer Pattern (Behavioral): Allows an object (subject) to notify other objects (observers) when its state changes.
import java.util.ArrayList;
import java.util.List;

// Subject
public class Subject {
    private List<Observer> observers = new ArrayList<>();
    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }

    public void attach(Observer observer){
        observers.add(observer);       
    }

    private void notifyAllObservers(){
        for (Observer observer : observers) {
            observer.update();
        }
    }    
}

// Observer
public abstract class Observer {
    protected Subject subject;
    public abstract void update();
}

// Concrete Observer
public class BinaryObserver extends Observer {
    public BinaryObserver(Subject subject){
        this.subject = subject;
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println( "Binary String: " + Integer.toBinaryString(subject.getState())); 
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Subject subject = new Subject();

        new BinaryObserver(subject);

        System.out.println("First state change: 15");   
        subject.setState(15);
    }
}

Expected Output:

First state change: 15
Binary String: 1111

4. Summary

In this tutorial, we covered the basics of design patterns, their types, and how to apply them in Java. We examined the Singleton, Adapter, and Observer patterns with code examples.

To continue learning, explore other design patterns such as Factory, Prototype, and Composite. The "Gang of Four" book is a great resource for learning design patterns.


5. Practice Exercises

  1. Implement the Factory design pattern in Java. (Hint: This pattern provides a way to delegate the instantiation logic to child classes.)

  2. Implement the Strategy design pattern in Java. (Hint: This pattern allows a client to choose an algorithm from a family of algorithms at runtime.)

Solutions to these exercises are left to the reader as a challenge. For further practice, reimplement the examples in this tutorial and modify them to suit different scenarios.