Last active
November 29, 2018 23:07
-
-
Save drenther/2db9a858617cfd333b2ff585c8ef02d0 to your computer and use it in GitHub Desktop.
Behavioural Pattern - Observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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