代理模式

  • 代理模式是为一个对象提供一个代用品,或占位符,以便控制对它的访问。
  • 对接口进行一定程度的隐藏,用于封装复杂类
  • 缓存代理比较常见。如果传递进来的参数跟以前一致,则可以直接返回前面存储的运算结果。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Car {
a: number = 1
b: number = 2
c: number = 3
d: number =4
name:string = 'name'
test(){
console.log('this is test')
}
}
class CarProxy {
private car: Car
name:number
constructor(){
if(this.car === null){
this.car = new Car
}
this.name = this.car.name
}
test(){
this.car.test()
}
}

参考链接