责任链模式 Golang

责任链模式

责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。
这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
应用实例: 消息过滤器, 权限拦截器

优点 和 缺点

优点

  1. 降低耦合度。它将请求的发送者和接收者解耦
  2. 增加新的请求处理类很方便
  3. 简化对象, 使的对象不需要知道的结构

缺点

  1. 不能保证请求一定被接受
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
type Handle interface {
SetNext(next Handle)
GetNext() Handle
HandleRequest(request string)
}
type ConcreteHandle1 struct {
next Handle
}

func (handle *ConcreteHandle1) SetNext(next Handle) {
handle.next = next
}
func (handle *ConcreteHandle1) GetNext() Handle {
return handle.next
}
func (handle *ConcreteHandle1) HandleRequest(request string) {
if request == "one" {
fmt.Println("1 response")
} else {
if handle.GetNext() != nil {
handle.GetNext().HandleRequest(request)
} else {
fmt.Println("No one handle")
}
}
}

type ConcreteHandle2 struct {
next Handle
}

func (handle *ConcreteHandle2) SetNext(next Handle) {
handle.next = next
}

func (handle *ConcreteHandle2) GetNext() Handle {
return handle.next
}
func (handle *ConcreteHandle2) HandleRequest(request string) {
if request == "two" {
fmt.Println("2 response")
} else {
if handle.GetNext() != nil {
handle.GetNext().HandleRequest(request)
} else {
fmt.Println("No one handle")
}
}
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2018 - 2021 Noonde All Rights Reserved.

UV : | PV :