享元
复用大量对象共有的不变状态。
结构型
说明
大量相似对象可只保存不同的外部状态;共享部分必须保持不可变。
分析
StylePool 按颜色缓存 Style,相同颜色的多个对象可共享同一个实例。每个对象只需保存自己的位置等外部状态,节省大量重复配置的内存。
第一次 Get blue 创建并放入池,第二次返回同一指针,所以相等比较为 true。若修改 first.Color,second 也会看到变化,因此不可变是共享前提,而不是语言自动保障。颜色种类无限增长时池也会无限增长,应按真实重复度评估收益,并明确池的生命周期。
查看图表代码
适用前提与边界
被共享的 Style 应视为不可变;并发访问缓存时还需要同步保护。 只有接口适配或独立变化确实存在时,才增加额外包装层。
示例输入与调用
go
pool := new(StylePool)
first := pool.Get("blue")
second := pool.Get("blue")
fmt.Println(first == second)运行输出
text
true完整 Go 示例
go
package main
import "fmt"
type Style struct{ Color string }
type StylePool struct{ items map[string]*Style }
func (p *StylePool) Get(color string) *Style {
if p.items == nil {
p.items = map[string]*Style{}
}
if p.items[color] == nil {
p.items[color] = &Style{Color: color}
}
return p.items[color]
}
func main() {
pool := new(StylePool)
first := pool.Get("blue")
second := pool.Get("blue")
fmt.Println(first == second)
}继续阅读
- 设计意图与对象责任
- 设计意图与对象责任
- 设计意图与对象责任