Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 18, 2019 02:44
Show Gist options
  • Save rxluz/85b6741992f7387c4a4d601fd32392cc to your computer and use it in GitHub Desktop.
Save rxluz/85b6741992f7387c4a4d601fd32392cc to your computer and use it in GitHub Desktop.
JS Design Patterns: State, see more at: https://medium.com/p/4a8e1f30b62d
/* STATE PATTERN EXAMPLE */
class TVRemoteChannel1State {
displayStatus() {
console.log("Hello now watch sports on channel 1");
}
}
class TVRemoteChannel2State {
displayStatus() {
console.log("Hello, watch a serie on channel 2");
}
}
class TVRemoteChannel3State {
displayStatus() {
console.log("Hello, watch the daily news on channel 3");
}
}
class TVRemoteWithStatePattern {
constructor() {
this.channel = 1;
this.channelInstances = {
1: new TVRemoteChannel1State(),
2: new TVRemoteChannel2State(),
3: new TVRemoteChannel3State(),
};
}
setChannel(channel) {
this.channel = channel;
}
watch() {
this.channelInstances[this.channel].displayStatus();
}
}
const TVRemoteInstance1 = new TVRemoteWithStatePattern();
TVRemoteInstance1.setChannel(1);
TVRemoteInstance1.watch();
TVRemoteInstance1.setChannel(2);
TVRemoteInstance1.watch();
TVRemoteInstance1.setChannel(3);
TVRemoteInstance1.watch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment