Skip to content

Instantly share code, notes, and snippets.

@wolivera
Created July 12, 2022 17:47
Show Gist options
  • Save wolivera/22faf7873db052729c32b1591d3db88d to your computer and use it in GitHub Desktop.
Save wolivera/22faf7873db052729c32b1591d3db88d to your computer and use it in GitHub Desktop.
GoF Visitor
class Player {
constructor (name, points, gems) {
this.name = name;
this.points = points;
this.gems = gems;
}
accept (visitor) {
visitor.visit(this);
}
getName () {
return this.name;
}
getPoints () {
return this.points;
}
setPoints (pts) {
this.points = pts;
}
getGems () {
return this.gems;
}
setGems (gems) {
this.gems = gems;
}
}
class AddPoints {
constructor() {
this.visit = function (player) {
player.setPoints(player.getPoints() * 1.1);
}
}
};
class AddGems {
constructor() {
this.visit = function (player) {
player.setGems(player.getGems() + 2);
}
}
}
const players = [
new Player("John", 10000, 10),
new Player("Mary", 20000, 21),
];
const extraPoints = new AddPoints();
const extraGems = new AddGems();
for (let i = 0, len = players.length; i < len; i++) {
const player = players[i];
player.accept(extraPoints);
player.accept(extraGems);
console.log(player.getName() + ": received " + player.getPoints() +
" extra points and " + player.getGems() + " extra gems");
}
// John: received 11000 extra points and 12 extra gems
// Mary: received 22000 extra points and 23 extra gems
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment