飞雪连天射白鹿,笑书神侠倚碧鸳

0%

【23种设计模式】12享元模式

描述:蝇量模式,共享对象支持大量的细粒度对象,内/外部状态,共享/非共享
优点:减少对象创建,降低内存
缺点:外部状态不随内部改变,提高复杂性

应用:缓冲池,连接池,相似对象


classDiagram
  class Flyweight {
    <>
    +doOperation(extrinsicState  string)* void
  }
  class ConcreteFlyweight{
    -intrinsicState : string
    constructor(intrinsicState : string)
    +doOperation(extrinsicState : string)  void
  }
  class flyweightObject{
    <>
    [key : string] : Flyweight
  }
  class FlyweightFactory {
    -flyweights : flyweightObject
    constructor()
    +getFlyweight(intrinsicState : string)  Flyweight
  }
  Flyweight <|-- ConcreteFlyweight:继承
  flyweightObject --o FlyweightFactory :聚合
  Flyweight --o FlyweightFactory :聚合
  • 抽象类,定义对象的内部,外部状态的接口
    • 产品类的具体实现,实现其方法
  • 享元工厂,返回具体实现的产品类
  • 实例话一个工厂,通过工厂获取抽象类的实现,并缓存这些实例,调用实例的方法,即类的公有方法
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
abstract class Flyweight {
public abstract doOperation(extrinsicState : string) : void;
}
class ConcreteFlyweight extends Flyweight {
private intrinsicState : string;
constructor(intrinsicState : string) {
super();
this.intrinsicState = intrinsicState;
}
public doOperation(extrinsicState : string) : void {
console.log(`这是具体享元角色,内部状态为${this.intrinsicState},外部状态为${extrinsicState}`);
}
}
interface flyweightObject {
[key : string] : Flyweight
}
class FlyweightFactory {
private flyweights : flyweightObject;
constructor() {
this.flyweights = {};
}
public getFlyweight(intrinsicState : string) : Flyweight {
if (!this.flyweights[intrinsicState]) {
const flyweight : Flyweight = new ConcreteFlyweight(intrinsicState);
this.flyweights[intrinsicState] = flyweight;
}
return this.flyweights[intrinsicState];
}
}
function main() {
const factory : FlyweightFactory = new FlyweightFactory();
const flyweight1 : Flyweight = factory.getFlyweight("aa");
const flyweight2 : Flyweight = factory.getFlyweight("aa");
flyweight1.doOperation('x');
flyweight2.doOperation('y');
}
main()
听说,打赏我的人最后都找到了真爱
↘ 此处应有打赏 ↙
// 用户脚本