Design patterns are essential in software development, especially in object-oriented programming. This article will delve into some advanced design patterns in Java, focusing on object-oriented principles.

Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Here's how you can implement it in Java:

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

For more information on Singleton pattern, check out our Singleton Pattern Guide.

Factory Pattern

The Factory pattern is used to create objects without specifying the exact class of object that will be created. It allows the code to defer object creation until the time of its actual use.

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

public class Square implements Shape {
    public void draw() {
        System.out.println("Drawing Square");
    }
}

public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }
        return null;
    }
}

To learn more about the Factory pattern, visit our Factory Pattern Tutorial.

Observer Pattern

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

interface Observer {
    void update(String message);
}

class ConcreteObserver implements Observer {
    public void update(String message) {
        System.out.println("Observer received message: " + message);
    }
}

class Subject {
    private List<Observer> observers = new ArrayList<>();

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

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

To explore more about the Observer pattern, read our Observer Pattern Explanation.

Conclusion

These are just a few examples of advanced design patterns in Java. Mastering these patterns can greatly enhance your object-oriented programming skills.

Java Design Patterns