-
Notifications
You must be signed in to change notification settings - Fork 2
/
Prototype.ts
49 lines (41 loc) · 1.02 KB
/
Prototype.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
interface CarPrototype {
clone(): CarPrototype
}
class Audi implements CarPrototype {
clone(): CarPrototype {
return new Audi()
}
}
class Benz implements CarPrototype {
clone(): CarPrototype {
return new Benz()
}
}
class BMW implements CarPrototype {
clone(): CarPrototype {
return new BMW()
}
}
abstract class CarFactory {
abstract createCar(brand: string): CarPrototype;
}
class ChineseCarFactory extends CarFactory {
private brands: { [brand: string]: CarPrototype; } = {};
constructor() {
super()
this.brands['Audi'] = new Audi()
this.brands['Benz'] = new Benz()
this.brands['BMW'] = new BMW()
}
createCar(brand: string): CarPrototype {
return this.brands[brand].clone()
}
}
// USAGE:
const factory = new ChineseCarFactory()
const prototypes = ['Audi', 'Benz', 'BMW'].map((brand) => {
return factory.createCar(brand)
})
console.log(prototypes)
// OUTPUT:
// [Audi: {}, Benz: {}, BMW: {}]