責任鏈模式是什么
責任鏈模式是一種行為設計模式, 允許你將請求沿著處理者鏈進行發送, 收到請求后, 每個處理者均可對請求進行處理, 或將其傳遞給鏈上的下個處理者,
為什么要用責任鏈模式
如果有多個物件可以處理同一個請求,具體哪個物件處理該請求由運行時刻自動確定,或者所需處理者及其順序必須在運行時進行改變, 可以使用責任鏈模式,
責任鏈模式怎么實作
病人來訪時, 他們首先都會去前臺(reception),然后是看醫生(doctor)、取藥(medical),最后結賬(cashier),也就是說,病人需要通過一條部門鏈,每個部門都在完成其職能后將病人進一步沿著鏈條輸送,
department.go 處理者介面
package responsibility
type department interface {
execute(*patient)
setNext(department)
}
// 病人
type patient struct {
name string
registrationDone bool
doctorCheckUpDone bool
medicineDone bool
paymentDone bool
}
reception.go 前臺
package responsibility
import "fmt"
type reception struct {
next department
}
func (r *reception) execute(p *patient) {
if p.registrationDone {
fmt.Println("Patient registration already done")
r.next.execute(p)
return
}
fmt.Println("Reception registering patient")
p.registrationDone = true
r.next.execute(p)
}
func (r *reception) setNext(next department) {
r.next = next
}
doctor.go 醫生
package responsibility
import "fmt"
type doctor struct {
next department
}
func (d *doctor) execute(p *patient) {
if p.doctorCheckUpDone {
fmt.Println("Doctor checkup already done")
d.next.execute(p)
return
}
fmt.Println("Doctor checking patient")
p.doctorCheckUpDone = true
d.next.execute(p)
}
func (d *doctor) setNext(next department) {
d.next = next
}
medical.go 取藥
package responsibility
import "fmt"
type medical struct {
next department
}
func (m *medical) execute(p *patient) {
if p.medicineDone {
fmt.Println("Medicine already given to patient")
m.next.execute(p)
return
}
fmt.Println("Medical giving medicine to patient")
p.medicineDone = true
m.next.execute(p)
}
func (m *medical) setNext(next department) {
m.next = next
}
cashier.go 結賬
package responsibility
import "fmt"
type cashier struct {
next department
}
func (c *cashier) execute(p *patient) {
if p.paymentDone {
fmt.Println("Payment Done")
}
fmt.Println("Cashier getting money from patient patient")
}
func (c *cashier) setNext(next department) {
c.next = next
}
example.go 呼叫示例
package responsibility
func Example() {
cashier := &cashier{}
//Set next for medical department
medical := &medical{}
medical.setNext(cashier)
//Set next for doctor department
doctor := &doctor{}
doctor.setNext(medical)
//Set next for reception department
reception := &reception{}
reception.setNext(doctor)
//Patient visiting
patient := &patient{name: "abc"}
reception.execute(patient)
}
優點
- 降低了物件之間的耦合度,該模式使得一個物件無須知道到底是哪一個物件處理其請求以及鏈的結構,發送者和接收者也無須擁有對方的明確資訊,
- 增強了系統的可擴展性,可以根據需要增加新的請求處理類,滿足開閉原則,
- 增強了給物件指派職責的靈活性,當作業流程發生變化,可以動態地改變鏈內的成員或者調動它們的次序,也可動態地新增或者洗掉責任,
- 責任鏈簡化了物件之間的連接,每個物件只需保持一個指向其后繼者的參考,不需保持其他所有處理者的參考,這避免了使用眾多的 if 或者 if···else 陳述句,
- 責任分擔,每個類只需要處理自己該處理的作業,不該處理的傳遞給下一個物件完成,明確各類的責任范圍,符合類的單一職責原則,
缺點
- 不能保證每個請求一定被處理,由于一個請求沒有明確的接收者,所以不能保證它一定會被處理,該請求可能一直傳到鏈的末端都得不到處理,
- 對比較長的職責鏈,請求的處理可能涉及多個處理物件,系統性能將受到一定影響,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/458405.html
標籤:設計模式
上一篇:談談微服務
下一篇:行為型:四. 責任鏈模式
