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.
Top comments (0)