责任链模式的定义:它是一种行为设计模式,请求沿着处理器链传递。收到请求后,每个处理器都可以处理请求或将其传递给链中的下一个处理器。在实际工作中,我们经常会遇到功能扩展,这可能会导致代码越来越臃肿或者逻辑越来越复杂。维护的程序员也可能不止一个,这也会造成一些混乱。责任链模式将解决这个问题。添加功能时,只需在链上添加处理器即可。不同的维护者维护他们自己的处理程序。职责链模型满足单一职责原则,请求和处理器解耦,只要将请求发送给一个处理器即可;每个处理器也完成自己的功能。责任链模式满足开闭原则。可以在不更改现有代码的情况下将新的处理程序添加到程序中。在责任链模式中,可以控制处理请求的顺序。我们来看代码实现:我们来模拟一下最高指挥部对各个作战单位下达命令的情况。请求者是最高指挥部(HighCommand),处理者包括Artillery、MissileForce和NuclearForce。每个单位分别处理最高指挥部下达的攻击命令。UML图如下:interface.go文件:packagemaintypeForcesinterface{Execute(*HighCommand)SetNext(Forces)}artillery.go文件:packagemainimport"fmt"typeArtillerystruct{nextForces}func(f*Artillery)Execute(command*HighCommand){ifcommand.ShowCommand()=="shellattack"{fmt.Println("ShellAttack!")return}fmt.Println("Sendtonext")f.next.Execute(command)}func(f*Artillery)SetNext(nextForces){f.next=next}missileForce.go文件:packagemainimport"fmt"typeMissileForcestruct{nextForces}func(f*MissileForce)Execute(command*HighCommand){ifcommand.ShowCommand()=="导弹攻击"{fmt.Println("导弹攻击!")return}fmt.Println("发送到下一个")f.next.Execute(command)}func(f*MissileForce)SetNext(nextForces){f.next=next}nuclearForce.go文件:packagemainimport"fmt"typeNuclearForcestruct{nextForces}func(f*NuclearForce)Execute(command*HighCommand){ifcommand.ShowCommand()=="核攻击"{fmt.Println("NuclearAttack!")return}fmt.Println("Sendtonext")f.next.Execute(command)}func(f*NuclearForce)SetNext(nextForces){f.next=next}end.go文件(链尾):packagemaintypeEndChainstruct{}func(f*EndChain)Execute(command*HighCommand){}func(f*EndChain)SetNext(nextForces){}client.go文件:packagemaintypeHighCommandstruct{namestring}func(c*HighCommand)ShowCommand()string{returnc.name}main.gofile:packagemainfuncmain(){//设置链结束:=&EndChain{}nuclearForce:=&NuclearForce{}nuclearForce.SetNext(结束)missileForce:=&MissileForce{}missileForce.SetNext(nuclearForce)artillery:=&Artillery{}artillery.SetNext(missileForce)command:=&HighCommand{name:"nuclearattack"}artillery.Execute(command)}gorun*。go可以运行这个例子,结果是:
