Search This Blog

2023/08/30

Factory Design Pattern in node.js

 class Product {

constructor(name, price) {
this.name = name;
this.price = price;
}

getInfo() {
return `Product: ${this.name}, Price: ${this.price}`;
}
}

class ConcreteProductA extends Product {
constructor(name, price) {
super(name, price);
}
}

class ConcreteProductB extends Product {
constructor(name, price) {
super(name, price);
}
}

class ProductFactory {
createProduct(type, name, price) {
switch (type) {
case 'A':
return new ConcreteProductA(name, price);
case 'B':
return new ConcreteProductB(name, price);
default:
throw new Error('Invalid product type');
}
}
}

const factory = new ProductFactory();

const productA = factory.createProduct('A', 'Product A', 100);
const productB = factory.createProduct('B', 'Product B', 200);

console.log(productA.getInfo()); // Output: Product: Product A, Price: 100
console.log(productB.getInfo()); // Output: Product: Product B, Price: 200

No comments:

Post a Comment