Famousmai's blog Famousmai's blog
首页
👍 网站介绍
💯 编程分享
✍️ 生活感悟
🎮 游戏人生
📈 网站动态
💌 收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Famous Mai

爱玩辅助的后端小哥
首页
👍 网站介绍
💯 编程分享
✍️ 生活感悟
🎮 游戏人生
📈 网站动态
💌 收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 算法

  • 学习笔记

  • 踩坑记录

  • 面试分享

  • 技术方案文章梳理

  • 设计模式

    • 设计模式介绍
    • 单例模式
    • 策略模式
      • 代码实现
  • 编程分享
  • 设计模式
famousmai
2023-03-13
目录

策略模式

# 代码实现

package main

import "fmt"

type EvictionAlgo interface {
	evict(c *Cache)
}

type Fifo struct {
}

func (l *Fifo) evict(c *Cache) {
	fmt.Println("Evicting by Fifo strategy")
}

type Lru struct {
}

func (l *Lru) evict(c *Cache) {
	fmt.Println("Evicting by Lru strategy")
}

type Lfu struct {
}

func (l *Lfu) evict(c *Cache) {
	fmt.Println("Evicting by Lfu strategy")
}

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")

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
编辑 (opens new window)
上次更新: 2023/03/13, 15:09:59
单例模式

← 单例模式

最近更新
01
单例模式
03-05
02
设计模式介绍
03-05
03
04.排序
03-04
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Evan Xu | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式