-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
45 lines (37 loc) · 861 Bytes
/
proxy.js
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
/**
* Proxy
*
* Proxy is a structural design pattern that provides a surrogate or
* placeholder for another object, controlling access to it. It can
* add additional behavior to the object being proxied, such as
* lazy initialization, access control, logging, and more.
*/
class Foo {
do() {
return 'Foo: Doing something'
}
}
class ProxyFoo {
constructor(obj) {
this.obj = obj
}
do() {
if (this.checkAccess()) {
console.log('Proxy Foo: Access granted')
return this.obj.do()
} else {
console.log('Proxy Foo: Access denied')
return false
}
}
checkAccess() {
console.log('Proxy Foo: Checking access')
return true
}
}
const foo = new Foo()
const proxy = new ProxyFoo(foo)
console.log(proxy.do())
// Proxy Foo: Checking access
// Proxy Foo: Access granted
// Foo: Doing something