-
Notifications
You must be signed in to change notification settings - Fork 2
/
FactoryMethod.ts
52 lines (46 loc) · 1.17 KB
/
FactoryMethod.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
interface Product {
doSomething(): void;
}
interface Factory {
createProduct(name: string): Product;
}
class ConcreteProductA implements Product {
doSomething(): void {
console.log('Product A do this');
}
}
class ConcreteProductB implements Product {
doSomething(): void {
console.log('Product B do this');
}
}
class UnkownProduct implements Product {
doSomething(): void {
console.log('Product is unkown');
}
}
class ProductFactory implements Factory {
createProduct(name: string): Product {
switch(name) {
case 'product-a':
return new ConcreteProductA();
case 'product-b':
return new ConcreteProductB();
default:
return new UnkownProduct();
}
}
}
// USAGE:
const factory = new ProductFactory();
const product1 = factory.createProduct('product-a');
const product2 = factory.createProduct('product-b');
const product3 = factory.createProduct('product-c');
product1.doSomething();
product2.doSomething();
product3.doSomething();
// OUTPUT:
// "Product A do this"
// "Product A do this"
// "Product B do this"
// "Product is unkown"