享元模式(基于map的单例共享)

2021-03-01  本文已影响0人  小幸运Q

享元就是共享的概念,比如线程池、对象池、连接池等等。从对象中剥离出不发生改变且多个实例需要的重复数据,独立出一个享元,使多个对象共享,从而节省内存以及减少对象数量。

image.png image.png
package main

import "fmt"

//FlyWeight 接口
type FlyWeight interface {
    Operation()
}

//ConcreteFlyWeight FlyWeight接口的实现
type ConcreteFlyWeight struct {
    Key string
}

func (t ConcreteFlyWeight) Operation() {
    fmt.Println(t.Key)
}

//FlyWeightFactory 共享资源,核心在于map这个数据结构
type FlyWeightFactory struct {
    flys map[string]FlyWeight
}

func (t FlyWeightFactory) GetFlyWeight(key string) FlyWeight {
    if f, ok := t.flys[key]; !ok {
        f = ConcreteFlyWeight{Key: key}
        t.flys[key] = f
        return f
    } else {
        return f
    }
}

//Len 打印对象个数
func (t FlyWeightFactory) Len() int {
    return len(t.flys)
}

func main() {
    factory := FlyWeightFactory{flys: make(map[string]FlyWeight)}
    factory.GetFlyWeight("A").Operation()
    factory.GetFlyWeight("A").Operation()
    factory.GetFlyWeight("B").Operation()
    factory.GetFlyWeight("C").Operation()
    fmt.Println(factory.Len())
    return
}
上一篇下一篇

猜你喜欢

热点阅读