Created
April 7, 2019 17:45
-
-
Save alfonmga/8317ff61409a81cf5100af3428b0eb5b to your computer and use it in GitHub Desktop.
JavaScript Abstract Factory Pattern
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 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