11. 享元模式(Flyweight)
11. 享元模式(Flyweight)
问题:大量相似对象占用过多内存。
核心:把不变的部分(内在状态)共享,可变的部分(外在状态)外部传入。
class TextStyle {
constructor(font, size, color) {
this.font = font;
this.size = size;
this.color = color;
}
}
class StyleFactory {
#cache = new Map();
getStyle(font, size, color) {
const key = `${font}-${size}-${color}`;
if (!this.#cache.has(key)) {
this.#cache.set(key, new TextStyle(font, size, color));
}
return this.#cache.get(key);
}
}
const factory = new StyleFactory();
const s1 = factory.getStyle('Arial', 14, 'black');
const s2 = factory.getStyle('Arial', 14, 'black');
console.log(s1 === s2); // true — 共享同一个对象package flyweight
import "fmt"
type TextStyle struct {
Font string
Size int
Color string
}
type StyleFactory struct {
cache map[string]*TextStyle
}
func NewStyleFactory() *StyleFactory {
return &StyleFactory{cache: make(map[string]*TextStyle)}
}
func (f *StyleFactory) GetStyle(font string, size int, color string) *TextStyle {
key := fmt.Sprintf("%s-%d-%s", font, size, color)
if _, ok := f.cache[key]; !ok {
f.cache[key] = &TextStyle{Font: font, Size: size, Color: color}
}
return f.cache[key]
}