美文网首页
享元模式(基于map的单例共享)

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

作者: 小幸运Q | 来源:发表于2021-03-01 00:41 被阅读0次

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

    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
    }
    

    相关文章

      网友评论

          本文标题:享元模式(基于map的单例共享)

          本文链接:https://www.haomeiwen.com/subject/vqgdfltx.html