Factory Pattern
CreationalWhat is it?
Provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
Why use it?
The Factory pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This is useful when a class can't anticipate the class of objects it needs to create or when it wants to delegate the responsibility of instantiation to subclasses. It promotes loose coupling by removing the need for the code to depend on concrete classes.
Code Example
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Factory Pattern Example
class Vehicle {
constructor(type, brand, model) {
this.type = type;
this.brand = brand;
this.model = model;
}
getInfo() {
return `${this.type}: ${this.brand} ${this.model}`;
}
}
class VehicleFactory {
static createVehicle(type, brand, model) {
switch(type) {
case 'car':
return new Car(brand, model);
case 'truck':
return new Truck(brand, model);
case 'motorcycle':
return new Motorcycle(brand, model);
default:
throw new Error(`Unknown vehicle type: ${type}`);
}
}
}
class Car extends Vehicle {
constructor(brand, model) {
super('Car', brand, model);
this.doors = 4;
this.wheels = 4;
}
honk() {
return 'Beep beep!';
}
}
class Truck extends Vehicle {
constructor(brand, model) {
super('Truck', brand, model);
this.doors = 2;
this.wheels = 6;
this.loadCapacity = '5000kg';
}
honk() {
return 'HONK HONK!';
}
}
class Motorcycle extends Vehicle {
constructor(brand, model) {
super('Motorcycle', brand, model);
this.wheels = 2;
}
honk() {
return 'Beep!';
}
}
// Usage
const car = VehicleFactory.createVehicle('car', 'Toyota', 'Camry');
const truck = VehicleFactory.createVehicle('truck', 'Ford', 'F-150');
const motorcycle = VehicleFactory.createVehicle('motorcycle', 'Harley-Davidson', 'Sportster');
console.log(car.getInfo()); // Car: Toyota Camry
console.log(truck.honk()); // HONK HONK!
console.log(motorcycle.wheels); // 2
Quick Facts
- Category
- Creational
- Common Use Cases
- Object creation, instance management