Sobes.tech
Middle+

What are behavioral patterns?

sobes.tech AI

Answer from AI

Behavioral design patterns describe interactions between objects and the distribution of responsibilities. They focus on algorithms and assigning responsibilities among objects.

Main behavioral patterns:

  • Chain of Responsibility: Passing a request along a chain of handlers. Each handler decides whether to process the request or pass it further.
  • Command: Encapsulates a request to perform a specific action as an object, allowing clients to be parameterized with different requests, queue requests, log them, and support undo operations.
  • Iterator: Provides sequential access to elements of a composite object without exposing its internal representation.
  • Mediator: Defines an object that encapsulates the interaction between a set of objects. The mediator promotes loose coupling by preventing objects from referring to each other explicitly.
  • Memento: Allows saving and restoring an object's external state without violating encapsulation.
  • Observer: Defines a one-to-many dependency between objects. When one object changes its state, all its dependents are notified and updated automatically.
  • State: Allows an object to alter its behavior when its internal state changes. The object appears to change its class.
  • Strategy: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
  • Template Method: Defines the skeleton of an algorithm in an operation, leaving some steps to be implemented by subclasses. It allows subclasses to redefine certain steps of an algorithm without changing its structure.
  • Visitor: Represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements.
# Example of the Observer pattern
class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        # Add an observer
        self._observers.append(observer)

    def detach(self, observer):
        # Remove an observer
        self._observers.remove(observer)

    def notify(self):
        # Notify all observers
        for observer in self._observers:
            observer.update(self)

class Observer:
    def update(self, subject):
        # Method to update observer's state
        print(f"Observer updated. Subject state: {subject._state}")

# Usage
subject = Subject()
observer1 = Observer()
observer2 = Observer()

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

subject._state = "New state"
subject.notify() # Calls update on observers

Behavioral patterns help improve code readability, maintainability, and extensibility by managing complex interactions between objects.