Search⌘ K
AI Features

Challenge: Solution Review

Explore the implementation of a flyweight factory pattern in JavaScript to efficiently manage dress objects and prevent duplicate instances. Learn how to create and control unique Dress instances by serialNumber, enhancing your understanding of structural design patterns for coding interviews.

We'll cover the following...

Solution #

Node.js
class Dress{
constructor(serialNumber,type,color,designer,availability){
this.serialNumber = serialNumber
this.type = type
this.color = color
this.designer = designer
this.availability = availability
this.price = 0
}
dressPrice(){
if(this.type == "maxi"){
this.price = 1000
}
if(this.type == "gown"){
this.price = 2000
}
if(this.type = "skirt"){
this.price = 500
}
return this.price
}
}
class DressFactory {
constructor() {
this.existingDresses = {}
}
createDress(serialNumber,type,color, designer, availability) {
var exists = this.existingDresses[serialNumber]
if (!!exists) {
return this.existingDresses[serialNumber]
}
else {
var dress = new Dress(serialNumber,type,color, designer, availability)
this.existingDresses[serialNumber]= dress
return dress
}
}
}
const factory = new DressFactory()
const pinkdress1 = factory.createDress("#123","skirt","pink","Zara","yes")
const pinkdress2 = factory.createDress("#123","skirt","pink","Zara","yes")
console.log(pinkdress1 === pinkdress2)
console.log(pinkdress1.dressPrice())
console.log(pinkdress2.dressPrice())

Explanation

As explained in the problem statement, we need to implement a functionality that doesn’t allow dresses with the same serialNumber to be made more than once. For this purpose, a flyweight factory can be used. Before we get into that, let’s look into the Dress class first.

class Dress{
  constructor(serialNumber,type,color,designer,availability){
    this.serialNumber = serialNumber
    this.type = type
    this.color = color
    this.designer = designer
    this.availability = availability
    this.price = 0
  }
 
...