概要
运用共享技术有效地支持大量细粒度的对象。
类图
需求
坦克提供两种机能,“发射”和“跑 ”,不同的坦克发射和跑的速度不一样,但是无论多少坦克,基本的发射和跑的机能是一样的。说以这里,对“发射”和“跑 ”采用享元模式处理。
设计
设计的关键就是,无论多坦克,最终“发射”和“跑 ”的机能只用一个就够了(就是控制“发射”和“跑 ”要单件)。
运行效果
代码
console.log('享元模式演示:');
class FlyweightFactory {
constructor() {
this.flyweithts = {};
}
getFlyweight(key) {
let flyweitht = this.flyweithts[key];
if (flyweitht == null) {
this.createFlyweight(key);
flyweitht = this.flyweithts[key];
}
return flyweitht;
}
createFlyweight(key) {
if (key == 'sort') {
this.flyweithts[key] = new SortFlyweight();
} else if (key == 'run') {
this.flyweithts[key] = new RunFlyweight();
}
}
}
class Flyweight {
constructor() {
this.baseFunction = "";
}
operation(extrinsic) {
console.log(this.baseFunction + extrinsic);
}
}
class SortFlyweight extends Flyweight {
constructor() {
super();
this.baseFunction = "发射炮弹:";
}
}
class RunFlyweight extends Flyweight {
constructor() {
super();
this.baseFunction = "跑:";
}
}
class Tank {
constructor(property, sort, run) {
this.property = property;
this.sort = sort;
this.run = run;
}
operation() {
this.sort.operation(this.property);
this.run.operation(this.property);
}
}
// 客户端
class Client {
main() {
let flyweightFactory = new FlyweightFactory();
let sort = flyweightFactory.getFlyweight('sort');
let run = flyweightFactory.getFlyweight('run');
let b70Tank = new Tank(70, sort, run);
b70Tank.operation();
let b50Tank = new Tank(50, sort, run);
b50Tank.operation();
}
}
var client = new Client();
client.main();
// key value 实验
/*
class Fun{
constructor(fun) {
this.fun = fun;
}
}
var map = {};
map['key1'] = new Fun(2);
map['key2'] = new Fun(3);
for (var o in map) {
console.log(map[o].fun);
}
*/
相关英语
flyweight:轻量级选手; 次最轻量级选手
factory:工厂; 制造厂; 代理店
operation:操作; 经营; [外科] 手术; [数][计] 运算
extrinsic:外在的;外来的;非固有的
concrete:混凝土的; 实在的,具体的; 有形的; vi. 凝结; vt. 使凝固; 用混凝土修筑; ...
intrinsic:本质的,固有的
unshared: 独享的; 专有的; 不共同参与的