Search This Blog

2023/08/30

Abstract Factory Design Pattern in javascript

 // Abstract Product A

class CPU {
constructor() {
this.architecture = '';
}

getInfo() {
return `CPU Architecture: ${this.architecture}`;
}
}

// Concrete Product A1
class IntelCPU extends CPU {
constructor() {
super();
this.architecture = 'x86';
}
}

// Concrete Product A2
class AMDCPU extends CPU {
constructor() {
super();
this.architecture = 'x86_64';
}
}

// Abstract Product B
class GPU {
constructor() {
this.vendor = '';
}

getInfo() {
return `GPU Vendor: ${this.vendor}`;
}
}

// Concrete Product B1
class NvidiaGPU extends GPU {
constructor() {
super();
this.vendor = 'Nvidia';
}
}

// Concrete Product B2
class AMGGPU extends GPU {
constructor() {
super();
this.vendor = 'AMD';
}
}

// Abstract Factory
class ComputerFactory {
createCPU() {}
createGPU() {}
}

// Concrete Factory 1
class HighPerformanceComputerFactory extends ComputerFactory {
createCPU() {
return new IntelCPU();
}

createGPU() {
return new NvidiaGPU();
}
}

// Concrete Factory 2
class BudgetComputerFactory extends ComputerFactory {
createCPU() {
return new AMDCPU();
}

createGPU() {
return new AMGGPU();
}
}

// Client Code
const highPerformanceFactory = new HighPerformanceComputerFactory();
const highPerformanceCPU = highPerformanceFactory.createCPU();
const highPerformanceGPU = highPerformanceFactory.createGPU();

console.log(highPerformanceCPU.getInfo()); // Output: CPU Architecture: x86
console.log(highPerformanceGPU.getInfo()); // Output: GPU Vendor: Nvidia

const budgetFactory = new BudgetComputerFactory();
const budgetCPU = budgetFactory.createCPU();
const budgetGPU = budgetFactory.createGPU();

console.log(budgetCPU.getInfo()); // Output: CPU Architecture: x86_64
console.log(budgetGPU.getInfo()); // Output: GPU Vendor: AMD

No comments:

Post a Comment