-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.ts
61 lines (48 loc) · 1.69 KB
/
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
/*
Hides complexety of object construction
Allows for multiple implementations of same basetype or interface
*/
module Factory {
/* Define interface or basetype */
export interface IProduct {
text: string;
price: number;
print():void;
}
/* Optionally have different implementations of the interface/basetype */
class ConsumerProduct implements IProduct {
text: string;
price: number;
constructor(text: string, listPrice: number) {
this.text = text;
this.price = Math.round(listPrice * 1.1);
}
print() {
write("Consumer product: " + this.text + " Price: " + this.price);
}
}
class BusinessProduct implements IProduct {
text: string;
price: number;
constructor(text: string, listPrice: number) {
this.text = text;
this.price = Math.round(listPrice * 1.2);
}
print() {
write("Business product: " + this.text + " Price: " + this.price);
}
}
/* Implement factory function to handle object construction */
export function create(type: string, name: string, listPrice: number) : IProduct {
if (type === "consumer") {
return new ConsumerProduct(name, listPrice);
} else if (type === "business") {
return new BusinessProduct(name, listPrice);
}
throw type + " is not a valid type";
}
}
var consumerProduct = Factory.create("consumer", "Jacket", 100);
var businessProduct = Factory.create("business", "Jacket", 100);
consumerProduct.print();
businessProduct.print();