一、简介
职责链模式:将请求的发送和接收解耦,让多个接收对象都有机会处理这个请求。将这些接收对象串成一条链,并沿着这条链传递这个请求,直到链上的某个接收对象能够处理它为止。
二、优点
- 分离发送者和接受者
- 易于扩展和维护
三、应用场景
- 有多个对象可以处理请求
- 动态添加、修改或删除请求处理器
四、UML类图
五、案例
日志打印,根据日志的不同等级,打印不同内容的日志。
package mainimport "fmt"const (ERROR = 0WARNING = 1INFO = 2
)type Logger interface {CanHandleMassage(logLever int) boolHandle(logLevel int, message string)
}type HandleChain struct {Logger LoggerNextHandleChain *HandleChain
}func (hc *HandleChain) SetNextHandleChain(nextHandleChain *HandleChain) {hc.NextHandleChain = nextHandleChain
}func (hc *HandleChain) Handle(logLevel int, message string) {if hc.Logger.CanHandleMassage(logLevel) {hc.Logger.Handle(logLevel, message)} else {hc.NextHandleChain.Handle(logLevel, message)}
}type ErrorLogger struct {Level int
}func NewErrorLogger() *HandleChain {return &HandleChain{Logger: &ErrorLogger{Level: ERROR}, NextHandleChain: &HandleChain{}}
}func (el *ErrorLogger) CanHandleMassage(logLever int) bool {return el.Level == logLever
}func (el *ErrorLogger) Handle(logLevel int, message string) {fmt.Printf("Error: %v\n", message)
}type WarningLogger struct {Level int
}func NewWarningLogger() *HandleChain {return &HandleChain{Logger: &WarningLogger{Level: WARNING}, NextHandleChain: &HandleChain{}}
}func (wl *WarningLogger) CanHandleMassage(logLever int) bool {return wl.Level == logLever
}func (wl *WarningLogger) Handle(logLevel int, message string) {fmt.Printf("Warning: %v\n", message)
}type InfoLogger struct {Level int
}func NewInfoLogger() *HandleChain {return &HandleChain{Logger: &InfoLogger{Level: INFO}, NextHandleChain: &HandleChain{}}
}func (il *InfoLogger) CanHandleMassage(logLever int) bool {return il.Level == logLever
}func (il *InfoLogger) Handle(logLevel int, message string) {fmt.Printf("Info: %v\n", message)
}func main() {errorLogger := NewErrorLogger()warningLogger := NewWarningLogger()infoLogger := NewInfoLogger()errorLogger.SetNextHandleChain(warningLogger)warningLogger.SetNextHandleChain(infoLogger)errorLogger.Handle(ERROR, "This is an error message")errorLogger.Handle(WARNING, "This is a warning message")errorLogger.Handle(INFO, "This is an info message")
}