Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active November 29, 2018 23:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/2db9a858617cfd333b2ff585c8ef02d0 to your computer and use it in GitHub Desktop.
Save drenther/2db9a858617cfd333b2ff585c8ef02d0 to your computer and use it in GitHub Desktop.
Behavioural Pattern - Observer
class Subject {
constructor() {
this._observers = [];
}
subscribe(observer) {
this._observers.push(observer);
}
unsubscribe(observer) {
this._observers = this._observers.filter(obs => observer !== obs);
}
fire(change) {
this._observers.forEach(observer => {
observer.update(change);
});
}
}
class Observer {
constructor(state) {
this.state = state;
this.initialState = state;
}
update(change) {
let state = this.state;
switch (change) {
case 'INC':
this.state = ++state;
break;
case 'DEC':
this.state = --state;
break;
default:
this.state = this.initialState;
}
}
}
// usage
const sub = new Subject();
const obs1 = new Observer(1);
const obs2 = new Observer(19);
sub.subscribe(obs1);
sub.subscribe(obs2);
sub.fire('INC');
console.log(obs1.state); // 2
console.log(obs2.state); // 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment