Sobes.tech
Junior — Middle

What is the pattern called that implements a subscription and notification mechanism upon event occurrence?

sobes.tech AI

Answer from AI

The pattern that implements a subscription and notification mechanism when events occur is called Observer.

In this pattern, there is a publisher object that maintains a list of subscribers (observers) and notifies them of changes in state or events. Subscribers implement an interface to receive notifications.

Example in PHP:

interface Observer {
    public function update($eventData);
}

class Subject {
    private $observers = [];

    public function attach(Observer $observer) {
        $this->observers[] = $observer;
    }

    public function notify($eventData) {
        foreach ($this->observers as $observer) {
            $observer->update($eventData);
        }
    }
}

This pattern is widely used for implementing event systems and callbacks.