Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created April 7, 2019 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfonmga/8317ff61409a81cf5100af3428b0eb5b to your computer and use it in GitHub Desktop.
Save alfonmga/8317ff61409a81cf5100af3428b0eb5b to your computer and use it in GitHub Desktop.
JavaScript Abstract Factory Pattern
class AudioDevice {
constructor () {
this.isPlaying = false;
this.currentTrack = null;
}
play (track) {
this.currentTrack = track;
this.isPlaying = true;
this.handlePlayCurrentAudioTrack();
}
handlePlayCurrentAudioTrack () {
throw new Error(`Subclasss responsibility error`)
}
}
class Boombox extends AudioDevice {
constructor () {
super()
}
handlePlayCurrentAudioTrack () {
// Play through the boombox speakers
}
}
class IPod extends AudioDevice {
constructor () {
super()
}
handlePlayCurrentAudioTrack () {
// Ensure headphones are plugged in
// Play through the ipod
}
}
const AudioDeviceType = {
Boombox: 'Boombox',
IPod: 'Ipod'
}
const AudioDeviceFactory = {
create: (deviceType) => {
switch (deviceType) {
case AudioDeviceType.Boombox:
return new Boombox();
case AudioDeviceType.IPod:
return new IPod();
default:
return null;
}
}
}
const boombox = AudioDeviceFactory
.create(AudioDeviceType.Boombox);
const ipod = AudioDeviceFactory
.create(AudioDeviceType.IPod);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment