forked from Sean-Bradley/Design-Patterns-In-TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy-concept.ts
More file actions
54 lines (45 loc) · 1.48 KB
/
Copy pathproxy-concept.ts
File metadata and controls
54 lines (45 loc) · 1.48 KB
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
// A Proxy Concept Example
interface ISubject {
// An interface implemented by both the Proxy and Real Subject
request(): void
// A method to implement
}
class RealSubject implements ISubject {
// The actual real object that the proxy is representing
enormousData: number[]
constructor() {
// hypothetically enormous amounts of data
this.enormousData = [1, 2, 3]
}
request() {
return this.enormousData
}
}
class ProxySubject implements ISubject {
// In this case the proxy will act as a cache for
// `enormous_data` and only populate the enormous_data when it
// is actually necessary
enormousData: number[]
realSubject: RealSubject
constructor() {
this.enormousData = []
this.realSubject = new RealSubject()
}
request() {
// Using the proxy as a cache, and loading data into it only if
// it is needed
if (this.enormousData.length === 0) {
console.log('pulling data from RealSubject')
this.enormousData = this.realSubject.request()
return this.enormousData
}
console.log('pulling data from Proxy cache')
return this.enormousData
}
}
// The Client
const PROXY_SUBJECT = new ProxySubject()
// Use the Subject. First time it will load the enormous amounts of data
console.log(PROXY_SUBJECT.request())
// Use the Subject again, but this time it retrieves it from the local cache
console.log(PROXY_SUBJECT.request())