Observer Design Pattern using Javascript
Bvnkumar
Posted on March 27, 2023
Design patterns are used to solve the specific problems in the software. Today we will be discussed about Observer Pattern in javascript.
Observer pattern is a software design pattern in which an object, called subject, maintains a list of its dependencies called observers and notify them automatically of any state changes.
For Example, In react if state changes then components will re-render accordingly. this process is similar to observer pattern functionality.
Below is the sample program for observer pattern.
function Subject(){
this.obeservers=[];
}
Subject.prototype={
add:function(fn){
this.obeservers.push(fn)
},
remove:function(fn){
this.obeservers=this.obeservers.filter(fun=>f!=fn)
},
notify:function(){
this.obeservers.forEach(fun=>{
fun.call()
})
}
}
function observer1(){
console.log("in the observer1")
}
function observer2(){
console.log("in the observer2")
}
const subject=new Subject();
subject.add(observer1);
subject.add(observer2);
subject.notify() // It will loop through all the observers.
In the above example, we have created the Subject constructor function. And it has observers list property, add, delete and notify methods.
Observers: It will have no.of observers.
Add: It will add observers(functions) to that list.
Remove: this method will remove the function from the list based on its argument.
Notify: this will notify all the observers in the list.
Comments and suggestions are always welcome.
Posted on March 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 23, 2023