Factory Method Pattern
Posted by Dustin Boston in Design Patterns.
The Factory Method Pattern is a creational design pattern that defines an interface for creating objects, allowing subclasses to decide which class to instantiate, promoting flexibility and scalability in object creation.
The Factory Method Pattern is a creational design pattern that defines an interface for creating objects in a superclass, while allowing subclasses to determine the specific type of objects to instantiate. This promotes flexibility and scalability in object creation, making it easier to manage and extend code.
Source Code Listing
code.ts
/* eslint-disable @typescript-eslint/no-extraneous-class */
type Product = Record<string, unknown>;
class ConcreteProduct1 implements Product {
[x: string]: unknown;
}
class ConcreteProduct2 implements Product {
[x: string]: unknown;
}
abstract class Creator {
operation(): void {
const product = this.factoryMethod(1); // Example usage, could be parameterized
if (product) {
// Use the product
}
}
abstract factoryMethod(id: number): Product | undefined;
}
class ConcreteCreator extends Creator {
factoryMethod(id: number): Product | undefined {
switch (id) {
case 1: {
return new ConcreteProduct1();
}
case 2: {
return new ConcreteProduct2();
}
default: {
return undefined;
} // Handle unknown product types
}
}
}
const example = {
run(): void {
const creator = new ConcreteCreator();
console.log(creator.factoryMethod(1));
console.log(creator.factoryMethod(2));
console.log(creator.factoryMethod(3)); // Now handles undefined
},
};
example.run();