基本信息
文件名称:Golang设计模式之责任链模式讲解和代码示例.docx
文件大小:16.71 KB
总页数:5 页
更新时间:2025-05-21
总字数:约2.97千字
文档摘要

Golang设计模式之责任链模式讲解和代码示例

目录Golang责任链模式讲解和代码示例概念示例department.go:处理者接口reception.go:具体处理者doctor.go:具体处理者medical.go:具体处理者cashier.go:具体处理者patient.gomain.go:客户端代码utput.txt:执行结果

Golang责任链模式讲解和代码示例

该模式允许多个对象来对请求进行处理,而无需让发送者类与具体接收者类相耦合。链可在运行时由遵循标准处理者接口的任意处理者动态生成。

概念示例

让我们来看看一个医院应用的责任链模式例子。医院中会有多个部门,如:

前台医生药房收银

病人来访时,他们首先都会去前台,然后是看医生、取药,最后结账。也就是说,病人需要通过一条部门链,每个部门都在完成其职能后将病人进一步沿着链条输送。

此模式适用于有多个候选选项处理相同请求的情形,适用于不希望客户端选择接收者(因为多个对象都可处理请求)的情形,还适用于想将客户端同接收者解耦时。客户端只需要链中的首个元素即可。

正如示例中的医院,患者在到达后首先去的就是前台。然后根据患者的当前状态,前台会将其指向链上的下一个处理者。

department.go:处理者接口

packagemain

typeDepartmentinterface{

execute(*Patient)

setNext(Department)

}

reception.go:具体处理者

packagemain

importfmt

//前台

typeReceptionstruct{

nextDepartment

func(r*Reception)execute(p*Patient){

ifp.registrationDone{

fmt.Println(Patientregistrationalreadydone)

r.next.execute(p)

fmt.Println(Receptionregisteringpatient)

p.registrationDone=true

r.next.execute(p)

func(r*Reception)setNext(nextDepartment){

r.next=next

}

doctor.go:具体处理者

packagemain

importfmt

typeDoctorstruct{

nextDepartment

func(d*Doctor)execute(p*Patient){

ifp.doctorCheckUpDone{

fmt.Println(Doctorcheckupalreadydone)

d.next.execute(p)

return

fmt.Println(Doctorcheckingpatient)

p.doctorCheckUpDone=true

d.next.execute(p)

func(d*Doctor)setNext(nextDepartment){

d.next=next

}

medical.go:具体处理者

packagemain

importfmt

typeMedicalstruct{

nextDepartment

func(m*Medical)execute(p*Patient){

ifp.medicineDone{

fmt.Println(Medicinealreadygiventopatient)

m.next.execute(p)

return

fmt.Println(Medicalgivingmedicinetopatient)

p.medicineDone=true

m.next.execute(p)

func(m*Medical)setNext(nextDepartment){

m.next=next

}

cashier.go:具体处理者

packagemain

importfmt

typeCashierstruct{

nextDepartment

func(c*Cashier)execute(p*Patient){

ifp.paymentDone{