forked from nic-dgl104-winter-2024/pattern-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabstract-factory.js
69 lines (55 loc) · 1.66 KB
/
abstract-factory.js
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
class Item {
constructor(name) {
this.name = name;
}
// Method to display the Item name
display() {
console.log(`Item: ${this.name}`);
}
}
// ConcreteItem1 class
class ConcreteItem1 extends Item {
constructor() {
super("ConcreteItem1");
}
}
// ConcreteItem2 class
class ConcreteItem2 extends Item {
constructor() {
super("ConcreteItem2");
}
}
// Factory method returns an instance of ConcreteItem based on the type passed as a parameter.
// The type is used to determine which ConcreteItem subclass to return.
// This allows the Creator class to be independent of the ConcreteItem subclasses.
// The Creator class is responsible for creating the ConcreteItem instances.
class Creator {
// Factory method
createItem(type) {
let item;
switch (type) {
case "type1":
item = new ConcreteItem1();
break;
case "type2":
item = new ConcreteItem2();
break;
default:
throw new Error("Invalid Item Type");
}
return item;
}
}
// Usage method for creating ConcreteItem instances based on the type passed as a parameter
const creator = new Creator();
const item1 = creator.createItem("type1");
item1.display();
// Output: Item: ConcreteItem1
const item2 = creator.createItem("type2");
item2.display();
// Output: Item: ConcreteItem2
/*
References
1. [GeeksforGeeks - Abstract Factory Pattern](https://www.geeksforgeeks.org/abstract-factory-pattern/)
2. [Refactoring Guru - Abstract Factory Design Pattern](https://refactoring.guru/design-patterns/abstract-factory)
*/