/
index.ts
59 lines (48 loc) · 1.02 KB
/
index.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
// https://en.wikipedia.org/wiki/Proxy_pattern
namespace ProxyPattern {
// Subject
interface ICar {
drive(): void;
}
// RealSubject
class Car implements ICar {
public drive(): void {
console.log("Car has been driven!");
}
}
class Driver {
private _age: number;
public get age() {
return this._age;
}
constructor(age: number) {
this._age = age;
}
}
// Proxy Object
class ProxyCar implements ICar {
private car: Car;
private driver: Driver;
constructor(driver: Driver) {
this.car = new Car();
this.driver = driver;
}
public drive(): void {
if (this.driver.age < 16) {
console.log("Sorry, the driver is too young to drive.");
} else {
this.car.drive();
}
}
}
// Client code
var proxy1 = new ProxyCar(new Driver(15)),
proxy2 = new ProxyCar(new Driver(25));
proxy1.drive();
proxy2.drive();
// Output
/*
Sorry, the driver is too young to drive.
Car has been driven!
*/
}