享元模式

享元模式的核心是共享对象,目的是节省内存开销,分为三个场景,共享对象的内部状态、共享对象的工厂函数、共享对象的外部函数。以共享单车为例,如下

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

// 内部状态
abstract class BikeFlyWeight{
protected state:number = 0; // 0为未使用,1为使用中
abstract ride(userName:string):void;
public getState():number{
return this.state;
}
public back(){
this.state = 0;
}
}

// 外部状态
class MoBikeFlyWeight extends BikeFlyWeight{
private bikeId:string = '';

constructor(bikeId:string){
super();
this.bikeId = bikeId;
}

ride(userName:string):void{
this.state = 1;
console.log(`${userName}${this.bikeId}号自行车`);
}
}

// 共享对象的工厂函数
class BikeFlyWeightFactory{
private static instance:BikeFlyWeightFactory = new BikeFlyWeightFactory();
private pool:Set<BikeFlyWeight> = new Set<BikeFlyWeight>();
private constructor(){
for(let i = 0;i<2;i++){
let bikeId:string = Math.floor(Math.random()*100000).toString(26);
this.pool.add(new MoBikeFlyWeight(bikeId));
}
}

public static getInstance():BikeFlyWeightFactory{
return BikeFlyWeightFactory.instance;
}

public getBike():BikeFlyWeight|null{
let resultBike:BikeFlyWeight = null;
for(let bike of this.pool){
if(bike.getState() === 0){
resultBike = bike;
break;
}
}
return resultBike;
}
}

// 客户端
class FlyWeightPattern{
public static main():void{
let bike1:BikeFlyWeight = BikeFlyWeightFactory.getInstance().getBike();
bike1.ride('Jonny');

let bike2:BikeFlyWeight = BikeFlyWeightFactory.getInstance().getBike();
bike2.ride('Candy');
bike2.back();

let bike3:BikeFlyWeight = BikeFlyWeightFactory.getInstance().getBike();
bike3.ride('Amy');

console.log(bike2===bike3); //是同一辆单车

bike3.back();

console.log(bike1===bike3); //不是同一辆单车
}
}

FlyWeightPattern.main();