Search This Blog

2023/04/19

Observer Design Pattern

In the Observer pattern, there is a one-to-many relationship between objects where one
object (called the subject) maintains a list of its dependents (observers)
and notifies them automatically of any changes to its state.
The observers can then take appropriate action based on the updated state of the subject

class observer {

constructor(name) {
this.name = name
}

update() {
console.log(`${this.name} received update`)
}
}


class subject {
observers = []

addObserver(observer) {
this.observers.push(observer)
}

removeObserver(observer) {
let index = this.observers.indexOf(observer)
if (index > -1) {
this.observers.splice(index, 1)
}
}

notify() {
this.observers.forEach((obs) => {
obs.update()
})
}
}

var sub = new subject()

var ob1 = new observer("sangram")
var ob2 = new observer("sagar")
var ob3 = new observer("sachin")
var ob4 = new observer("mandar")

sub.addObserver(ob1)
sub.addObserver(ob2)
sub.addObserver(ob3)
sub.addObserver(ob4)

sub.notify()

sub.removeObserver(ob2)

sub.notify()

//Output:
sangram received update
sagar received update
sachin received update
mandar received update
sangram received update
sachin received update
mandar received update


Another Example:
class BirthdayReminder {
constructor() {
this.observers = [];
}

addObserver(observer) {
this.observers.push(observer);
}

removeObserver(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}

notifyObservers() {
const today = new Date();
const month = today.getMonth() + 1;
const day = today.getDate();
this.observers.forEach(observer => {
if (observer.month === month && observer.day === day) {
observer.notify();
}
});
}
}

class Person {
constructor(name, month, day) {
this.name = name;
this.month = month;
this.day = day;
}

notify() {
console.log(`Today is ${this.name}'s birthday!`);
}
}

// Usage
const birthdayReminder = new BirthdayReminder();

const person1 = new Person("Alice", 5, 20);
const person2 = new Person("Bob", 10, 15);
const person3 = new Person("Charlie", 4, 30);

birthdayReminder.addObserver(person1);
birthdayReminder.addObserver(person2);
birthdayReminder.addObserver(person3);

// Notify observers on their birthday
birthdayReminder.notifyObservers();


cron is not an example of the Observer pattern.
cron is a time-based job scheduler in Unix-like
operating systems that allows you to schedule and
run recurring tasks at specified intervals.
It is not a design pattern in the sense of a
general solution to a recurring problem.

No comments:

Post a Comment