go 示例
最后更新于:2022-04-02 04:21:31
[TOC]
## 示例
### 切换算法策略
输出 ``` Evicting by lfu strtegy Evicting by lru strtegy Evicting by fifo strtegy ```
';
main.go
``` // 不同的 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") } ```输出 ``` Evicting by lfu strtegy Evicting by lru strtegy Evicting by fifo strtegy ```