Search⌘ K
AI Features

Challenge: Solution Review

Explore how to transform subclass inheritance into the decorator pattern in JavaScript. Understand the benefits of decorator functions to add multiple features dynamically to superhero objects, enabling flexible and scalable design solutions for coding interviews.

We'll cover the following...

Solution #

Node.js
class SuperHero {
constructor(name,power) {
this.name = name
this.power = power
}
}
function SuperHeroWithSword(superhero){
superhero.sword = true
superhero.hasSword= function(){
return `${this.name}'s power is ${this.power}, and he also has a sword now.`
}
return superhero;
}
function SuperHeroWithSuperSpeed(superhero) {
superhero.superSpeed = true
superhero.hasSuperSpeed= function(){
return `${this.name}'s power is ${this.power}, and he also has the super speed now.`
}
return superhero;
}
function SuperHeroWithSpeedandSword(superhero){
superhero.speedAndSword = true
superhero.hasSpeedAndSword = function(){
return `${this.name}'s power is ${this.power}, and he also has both super speed and a sword now.`
}
return superhero;
}
var superhero1 = new SuperHero("Fire Man", "Fire")
SuperHeroWithSword(superhero1)
console.log(superhero1.hasSword())
SuperHeroWithSuperSpeed(superhero1)
console.log(superhero1.hasSuperSpeed())
var superhero2 = new SuperHero("Ice Man", "Ice")
SuperHeroWithSpeedandSword(superhero2)
console.log(superhero2.hasSpeedAndSword())

Explanation

Let’s start by going through the original code, so we can understand how to modify it.

Node.js
class SuperHero {
constructor(name,power) {
this.name = name
this.power = power
}
}
class SuperHeroWithSword extends SuperHero{
constructor(name,power){
super(name,power)
this.sword = true
}
hasSword(){
return `${this.name}'s power is ${this.power}, and he also has a sword now.`
}
}
class SuperHeroWithSuperSpeed extends SuperHero{
constructor(name,power){
super(name,power)
this.superSpeed = true
}
hasSuperSpeed(){
return `${this.name}'s power is ${this.power}, and he also has the super speed now.`
}
}
class SuperHeroWithSpeedandSword extends SuperHero{
constructor(name,power){
super(name,power)
this.speedAndSword = true
}
hasSpeedAndSword(){
return `${this.name}'s power is ${this.power}, and he also has both super speed and a sword now.`
}
}
var superhero1 = new SuperHeroWithSword("Fire Man", "Fire")
console.log(superhero1.hasSword())
var superhero2 = new SuperHeroWithSuperSpeed("Fire Man", "Fire")
console.log(superhero2.hasSuperSpeed())
var superhero3 = new SuperHeroWithSpeedandSword("Ice Man", "Ice")
console.log(superhero3.hasSpeedAndSword())

You can see that the original code implements inheritance to create a customized character. It has a SuperHero class that looks like:

class SuperHero {
  constructor(name,power) {
    this.name = name
    this.power = power
  }
}

Each SuperHero instance will have a name and power. Next, there are three child classes, all of which extend the functionality of the SuperHero class like so:

 ...