Skip to content

Commit 8b2ccb6

Browse files
docs(design_pattern): 添加设计模式相关代码示例
- 新增多个设计模式的 Go 语言实现示例 - 包括创建型、结构型和行为型设计模式 - 每个设计模式都有对应的代码文件和解释
1 parent f983296 commit 8b2ccb6

File tree

24 files changed

+1304
-0
lines changed

24 files changed

+1304
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
)
7+
8+
type Context struct {
9+
request *http.Request
10+
w http.ResponseWriter
11+
index int
12+
handlers []HandlerFun
13+
}
14+
15+
func (c *Context) Next() {
16+
c.index++
17+
if c.index < len(c.handlers) {
18+
c.handlers[c.index](c)
19+
}
20+
}
21+
func (c *Context) Abort() {
22+
c.index = len(c.handlers)
23+
}
24+
25+
type HandlerFun func(*Context)
26+
type Engine struct {
27+
handlers []HandlerFun
28+
}
29+
30+
func (e *Engine) Use(f HandlerFun) {
31+
e.handlers = append(e.handlers, f)
32+
}
33+
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
34+
context := &Context{
35+
request: r,
36+
w: w,
37+
index: -1,
38+
handlers: e.handlers,
39+
}
40+
context.Next()
41+
}
42+
43+
func AuthMiddleware(c *Context) {
44+
fmt.Println("认证中间件")
45+
}
46+
func LogMiddleware(c *Context) {
47+
fmt.Println("日志中间件")
48+
c.Next()
49+
}
50+
func main() {
51+
r := &Engine{}
52+
r.Use(LogMiddleware)
53+
r.Use(AuthMiddleware)
54+
55+
fmt.Println("web server on :8080")
56+
http.ListenAndServe(":8080", r)
57+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type Command interface {
6+
Execute()
7+
}
8+
9+
type PrintCommand struct {
10+
Content string
11+
}
12+
13+
func (p PrintCommand) Execute() {
14+
fmt.Println("打印消息", p.Content)
15+
}
16+
17+
type SendEmail struct {
18+
To string
19+
Content string
20+
}
21+
22+
func (s SendEmail) Execute() {
23+
fmt.Println("发送邮件", s.To, s.Content)
24+
}
25+
26+
type SendTel struct {
27+
To string
28+
Content string
29+
}
30+
31+
func (s SendTel) Execute() {
32+
fmt.Println("发送短信", s.To, s.Content)
33+
}
34+
35+
type TaskQueue struct {
36+
Queue []Command
37+
}
38+
39+
func NewTaskQueue() *TaskQueue {
40+
return &TaskQueue{}
41+
}
42+
43+
func (t *TaskQueue) AddCommand(command Command) {
44+
t.Queue = append(t.Queue, command)
45+
}
46+
47+
func (t *TaskQueue) Command() {
48+
for _, command := range t.Queue {
49+
command.Execute()
50+
}
51+
}
52+
53+
func main() {
54+
queue := NewTaskQueue()
55+
queue.AddCommand(&PrintCommand{
56+
Content: "你好",
57+
})
58+
queue.AddCommand(&SendEmail{
59+
Content: "你好",
60+
To: "xxx@qq.com",
61+
})
62+
queue.AddCommand(&SendTel{
63+
Content: "你好",
64+
To: "11122223333",
65+
})
66+
queue.Command()
67+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
func main() {
9+
// 定义模板字符串
10+
const tmpl = `Hello, {{ Name }}! You are {{Age}} years old.`
11+
template := ParseTemplate(tmpl)
12+
res := template.Interpreter(&Context{
13+
Data: map[string]any{
14+
"Name": "fengfeng",
15+
"Age": 21,
16+
},
17+
})
18+
fmt.Println(res)
19+
}
20+
21+
type Context struct {
22+
Data map[string]any
23+
}
24+
25+
type Node interface {
26+
Interpreter(*Context) string
27+
}
28+
29+
type TextNode struct {
30+
Content string
31+
}
32+
33+
func (t *TextNode) Interpreter(ctx *Context) string {
34+
return t.Content
35+
}
36+
37+
type VarNode struct {
38+
Key string
39+
}
40+
41+
func (t *VarNode) Interpreter(ctx *Context) string {
42+
val, ok := ctx.Data[t.Key]
43+
if !ok {
44+
return ""
45+
}
46+
return fmt.Sprintf("%v", val)
47+
}
48+
49+
type Template struct {
50+
tree []Node
51+
}
52+
53+
func ParseTemplate(tmpl string) *Template {
54+
var template = new(Template)
55+
var index = 0
56+
for {
57+
startIndex := strings.Index(tmpl[index:], "{{")
58+
if startIndex == -1 {
59+
template.tree = append(template.tree, &TextNode{
60+
Content: tmpl[index:],
61+
})
62+
break
63+
}
64+
template.tree = append(template.tree, &TextNode{
65+
Content: tmpl[index : index+startIndex],
66+
})
67+
endIndex := strings.Index(tmpl[index+startIndex:], "}}")
68+
if endIndex == -1 {
69+
break
70+
}
71+
key := strings.TrimSpace(tmpl[index+startIndex+2 : index+startIndex+endIndex])
72+
template.tree = append(template.tree, &VarNode{
73+
Key: key,
74+
})
75+
index = index + startIndex + endIndex + 2
76+
}
77+
return template
78+
}
79+
func (t *Template) Interpreter(ctx *Context) string {
80+
var s string
81+
for _, node := range t.tree {
82+
s += node.Interpreter(ctx)
83+
}
84+
return s
85+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type Book struct {
6+
Title string
7+
}
8+
9+
type BookIterator struct {
10+
Books []*Book
11+
position int
12+
}
13+
14+
func NewBookIterator(book []*Book) *BookIterator {
15+
return &BookIterator{
16+
Books: book,
17+
position: 0,
18+
}
19+
}
20+
21+
type Iterator interface {
22+
HasNext() bool
23+
Next() *Book
24+
}
25+
26+
func (b *BookIterator) HasNext() bool {
27+
if b.position >= len(b.Books) {
28+
return false
29+
}
30+
return true
31+
}
32+
func (b *BookIterator) Next() *Book {
33+
if !b.HasNext() {
34+
return nil
35+
}
36+
book := b.Books[b.position]
37+
b.position++
38+
return book
39+
}
40+
41+
func IteratorFunc(iterator Iterator) {
42+
for iterator.HasNext() {
43+
book := iterator.Next()
44+
fmt.Println(book.Title)
45+
}
46+
}
47+
48+
func main() {
49+
book := []*Book{
50+
{Title: "Go开发"},
51+
{Title: "前端开发"},
52+
{Title: "XX开发"},
53+
}
54+
55+
bookIterator := NewBookIterator(book)
56+
IteratorFunc(bookIterator)
57+
58+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type Obj interface {
6+
SendMsg(string)
7+
RevMsg(string)
8+
}
9+
type Mediator interface {
10+
SendMsg(msg string, user Obj)
11+
}
12+
13+
type User struct {
14+
Name string
15+
mediator Mediator
16+
}
17+
18+
func (u User) SendMsg(msg string) {
19+
fmt.Printf("用户 %s 发了消息 %s\n", u.Name, msg)
20+
u.mediator.SendMsg(msg, u)
21+
}
22+
func (u User) RevMsg(msg string) {
23+
fmt.Printf("用户 %s 接收到消息 %s\n", u.Name, msg)
24+
}
25+
26+
type ChatRoom struct {
27+
users []User
28+
}
29+
30+
func (c *ChatRoom) Register(user User) {
31+
c.users = append(c.users, user)
32+
}
33+
func (c *ChatRoom) SendMsg(msg string, user Obj) {
34+
for _, u := range c.users {
35+
if u == user {
36+
continue
37+
}
38+
u.RevMsg(msg)
39+
}
40+
}
41+
42+
func main() {
43+
room := ChatRoom{}
44+
u1 := User{Name: "枫枫", mediator: &room}
45+
u2 := User{Name: "张三", mediator: &room}
46+
u3 := User{Name: "李四", mediator: &room}
47+
48+
room.Register(u1)
49+
room.Register(u2)
50+
room.Register(u3)
51+
52+
u1.SendMsg("你好啊")
53+
u2.SendMsg("吃了吗")
54+
u3.SendMsg("我吃了")
55+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type Node interface {
6+
SetState(state string)
7+
GetState() string
8+
}
9+
10+
type TextNode struct {
11+
state string
12+
}
13+
14+
func (t *TextNode) SetState(state string) {
15+
t.state = state
16+
}
17+
func (t *TextNode) GetState() string {
18+
return t.state
19+
}
20+
func (t *TextNode) Save() Memento {
21+
return &TextMemento{
22+
state: t.state,
23+
}
24+
}
25+
26+
type Memento interface {
27+
GetState() string
28+
}
29+
type TextMemento struct {
30+
state string
31+
}
32+
33+
func (t TextMemento) GetState() string {
34+
return t.state
35+
}
36+
37+
type Manage struct {
38+
states []Memento
39+
}
40+
41+
func (m *Manage) Save(t Memento) {
42+
m.states = append(m.states, t)
43+
}
44+
func (m *Manage) Back(index int) Memento {
45+
return m.states[index]
46+
}
47+
48+
func main() {
49+
manage := Manage{}
50+
text := TextNode{}
51+
text.SetState("1")
52+
manage.Save(text.Save())
53+
text.SetState("2")
54+
manage.Save(text.Save())
55+
fmt.Println(text.GetState())
56+
fmt.Println(manage.Back(0).GetState())
57+
}

0 commit comments

Comments
 (0)