Last active
May 31, 2022 01:24
-
-
Save mcsee/747c2a4a6bb3531966b7e98ad92924e3 to your computer and use it in GitHub Desktop.
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
// 1. Create a Polymorphic Hierarchy for every IF condition | |
// (if it doesn't already exist) | |
class MovieRate { | |
// If language permits this should be declared abstract | |
} | |
class PG13MovieRate extends MovieRate { | |
//2. Move every *IF Body* to the former abstraction | |
warnIfNotAllowed(age) { | |
if (age < 13) | |
throw new Error("You are not allowed to watch this movie"); | |
} | |
} | |
class AdultsOnlyMovieRate extends MovieRate { | |
//2. Move every *IF Body* to the former abstraction | |
warnIfNotAllowed(age) { | |
if (age < 18) | |
throw new Error("You are not allowed to watch this movie"); | |
} | |
} | |
class Movie { | |
constructor(rate) { | |
this.rate = rate; | |
} | |
} | |
class Moviegoer { | |
constructor(age) { | |
this.age = age; | |
} | |
watchMovie(movie) { | |
// 3. Replace IF Call by polymorphic method call | |
movie.rate.warnIfNotAllowed(this.age); | |
// watch movie | |
} | |
} | |
let theExorcist = new Movie(new AdultsOnlyMovieRate()); | |
let gremlins = new Movie(new PG13MovieRate()); | |
let jane = new Moviegoer(12); | |
// jane.watchMovie(theExorcist); | |
// Jane cannot watch the exorcist since she is 12 | |
// jane.watchMovie(gremlins); | |
// Jane cannot watch gremlins since she is 12 | |
let joe = new Moviegoer(16); | |
// joe.watchMovie(theExorcist); | |
// Joe cannot watch the exorcist since he is 16 | |
joe.watchMovie(gremlins); | |
// Joe CAN watch gremlins since he is 16 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment