🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 示例 ### 切换算法策略 <details> <summary>main.go</summary> ``` // 不同的 state 分别实接口的4种情况的处理流程 package main import "fmt" type evictionAlgo interface { evict(c *cache) // 设置策略 } type fifo struct { } func (l *fifo) evict(c *cache) { fmt.Println("Evicting by fifo strtegy") } type lru struct { } func (l *lru) evict(c *cache) { fmt.Println("Evicting by lru strtegy") } type lfu struct { } func (l *lfu) evict(c *cache) { fmt.Println("Evicting by lfu strtegy") } type cache struct { storage map[string]string evictionAlgo evictionAlgo capacity int maxCapacity int } func initCache(e evictionAlgo) *cache { storage := make(map[string]string) return &cache{ storage: storage, evictionAlgo: e, capacity: 0, maxCapacity: 2, } } // 设置移除算法 func (c *cache) setEvictionAlgo(e evictionAlgo) { c.evictionAlgo = e } func (c *cache) add(key, value string) { if c.capacity == c.maxCapacity { c.evict() } c.capacity++ c.storage[key] = value } func (c *cache) get(key string) { delete(c.storage, key) } func (c *cache) evict() { c.evictionAlgo.evict(c) c.capacity-- } func main() { lfu := &lfu{} cache := initCache(lfu) cache.add("a", "1") cache.add("b", "2") cache.add("c", "3") lru := &lru{} cache.setEvictionAlgo(lru) cache.add("d", "4") fifo := &fifo{} cache.setEvictionAlgo(fifo) cache.add("e", "5") } ``` </details> <br /> 输出 ``` Evicting by lfu strtegy Evicting by lru strtegy Evicting by fifo strtegy ```