-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabstract-factory.ts
107 lines (88 loc) · 2.6 KB
/
abstract-factory.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* **Abstract Factory**
*
* > "Provide an interface for creating families of related or dependent
* objects without specifying their concrete classes."
*
* This pattern builds on the regular Factory pattern, by adding
* another level of abstraction (no pun intented).
*
* We will provide our application with a factory instance (one of two possible)
* and let the application simply use it. This way, we can "dependency inject"
* an appropriate factory, allowing this second level of abstraction that
* the regular Factory pattern doesn't imply.
*
* The use of the factory itself, however, is exactly the same as in the
* ordinary Factory pattern.
*
* The result is a highly contained and separated distinction between the
* composition and usage of classes.
*
* @see https://refactoring.guru/design-patterns/abstract-factory
* @see https://en.wikipedia.org/wiki/Abstract_factory_pattern
* @see Page 87 in `Design Patterns - Elements of Reusable Object-Oriented Software`
*/
function abstractFactoryDemo() {
// Interfaces
interface AbstractFactory {
createPrimaryProduct(): AbstractProductA;
createSecondaryProduct(): AbstractProductB;
}
interface AbstractProductA {
doThis(): void;
}
interface AbstractProductB {
doThat(): void;
}
// Factories
class ChocolateFactory implements AbstractFactory {
createPrimaryProduct() {
return new ChocolateBar();
}
createSecondaryProduct() {
return new CandyWrapper();
}
}
class BicycleFactory implements AbstractFactory {
createPrimaryProduct() {
return new Bike();
}
createSecondaryProduct() {
return new Helmet();
}
}
// Chocolate factory products
class ChocolateBar implements AbstractProductA {
doThis() {
console.log('ChocolateBar doThis');
}
}
class CandyWrapper implements AbstractProductB {
doThat() {
console.log('CandyWrapper doThat');
}
}
// Bicycle factory products
class Bike implements AbstractProductA {
doThis() {
console.log('Bike doThis');
}
}
class Helmet implements AbstractProductB {
doThat() {
console.log('Helmet doThat');
}
}
// Let's use it!
function myApplication(factory: AbstractFactory) {
const productA = factory.createPrimaryProduct();
const productB = factory.createSecondaryProduct();
productA.doThis();
productB.doThat();
}
const chocolateFactory: AbstractFactory = new ChocolateFactory();
myApplication(chocolateFactory);
const bicycleFactory: AbstractFactory = new BicycleFactory();
myApplication(bicycleFactory);
}
abstractFactoryDemo();