Observer and Strategy Patterns

 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. This is commonly used in scenarios where an event from one object must trigger updates in other objects.


Key Points

- Establishes a one-to-many relationship between objects.

- Notifies multiple observers when the state of the subject changes.

- Decouples the subject from the observers.


Implementation Example

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

// Observer Interface
public interface Observer {
    void update(String message);
}

// Concrete Observer
public class ConcreteObserver implements Observer {
    private String name;

    public ConcreteObserver(String name) {
        this.name = name;
    }

    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

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

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

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

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

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

        Observer observer1 = new ConcreteObserver("Observer 1");
        Observer observer2 = new ConcreteObserver("Observer 2");

        subject.attach(observer1);
        subject.attach(observer2);

        subject.notifyObservers("State changed");
    }
}


Strategy Pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This allows the algorithm to vary independently from the clients that use it.


Key Points

- Defines a family of algorithms.

- Encapsulates each algorithm.

- Makes the algorithms interchangeable.

- Allows algorithms to be selected at runtime.


Implementation Example

// Strategy Interface
public interface Strategy {
    int doOperation(int num1, int num2);
}

// Concrete Strategies
public class Addition implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

public class Subtraction implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

public class Multiplication implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}

// Context Class
public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }

}
// Usage
public class Client {
    public static void main(String[] args) {
        Context context = new Context(new Addition());
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

        context = new Context(new Subtraction());
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

        context = new Context(new Multiplication());
        System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
    }
}


Comparison

- Observer Pattern:

  - Establishes a one-to-many relationship between objects.

  - Useful for implementing distributed event-handling systems.

  - Decouples the subject from the observers, allowing the subject to notify all observers when its state changes.


- Strategy Pattern:

  - Defines a family of interchangeable algorithms.

  - Allows the client to choose which algorithm to use at runtime.

  - Encapsulates the algorithms, making them easy to swap without modifying the client.


Both patterns promote flexibility and reusability, but they serve different purposes. The Observer pattern is mainly used for notifying multiple objects about state changes, whereas the Strategy pattern is used for selecting and applying algorithms dynamically.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....