定义
策略模式是一种行为型的设计模式,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户,或者认为把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理
代码
请先阅读 行为型设计模式 (refactoringguru.cn)。
一般来说可以使策略模式和简单工厂模式结合使用.
可以修改 cache.go 文件,如下
package main
type algorithmType int
const (
fifoTyp algorithmType = 0 + iota
lfuTyp
lruTyp
)
type Cache struct {
storage map[string]string
evictionAlgo EvictionAlgo
capacity int
maxCapacity int
}
func initCache(algoTyp algorithmType) *Cache {
var e EvictionAlgo
switch algoTyp {
case fifoTyp:
e = &Fifo{}
case lfuTyp:
e = &Lfu{}
case lruTyp:
e = &Lru{}
default:
panic("algorithm type error.")
}
storage := make(map[string]string)
return &Cache{
storage: storage,
evictionAlgo: e,
capacity: 0,
maxCapacity: 2,
}
}
func (c *Cache) setEvictionAlgo(algoTyp algorithmType) {
switch algoTyp {
case fifoTyp:
c.evictionAlgo = &Fifo{}
case lfuTyp:
c.evictionAlgo = &Lfu{}
case lruTyp:
c.evictionAlgo = &Lru{}
default:
panic("algorithm type error.")
}
}
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--
}
然后 main.go 文件中的代码可以重新修改成下面这样.
package main
func main() {
cache := initCache(lfuTyp)
cache.add("a", "1")
cache.add("b", "2")
cache.add("c", "3")
cache.setEvictionAlgo(lruTyp)
cache.add("d", "4")
cache.setEvictionAlgo(fifoTyp)
cache.add("e", "5")
}
完整代码地址: github/strategy 设计模式
可以使用下面的命令初始化和运行代码
go mod init strategy
go mod tidy
go run .
评论区