Skip to content

Instantly share code, notes, and snippets.

@mt40
Created January 31, 2024 04:42
Show Gist options
  • Save mt40/1de3449201bdbef1157245bdffff855a to your computer and use it in GitHub Desktop.
Save mt40/1de3449201bdbef1157245bdffff855a to your computer and use it in GitHub Desktop.
Design Pattern: Chain Of Responsibility
type ConsoleLogger struct {
next Logger
}
func (l *ConsoleLogger) Log(level LogLevel, text string) {
fmt.Printf("%s | %s\n", level, text)
if l.next != nil {
l.next.Log(level, text)
}
}
func TestConsoleLogger(t *testing.T) {
logger := &ConsoleLogger{}
expect := "haha"
logger.Log(Info, expect)
// check console output
}
type EmailLogger struct {
next Logger
}
func (l *EmailLogger) Log(level LogLevel, text string) {
if level == Error {
fmt.Printf("%s | sent alert email to me", level)
}
if l.next != nil {
l.next.Log(level, text)
}
}
type LogLevel string
const (
Info LogLevel = "info"
Error LogLevel = "error"
)
type Logger interface {
Log(level LogLevel, text string)
}
func NewLogger() Logger {
return &EmailLogger{
next: &ConsoleLogger{},
}
}
logger := NewLogger()
logger.Log(Info, "hello world")
logger.Log(Error, "the world has already ended due to zombies!")
// Output:
// info | hello world
// error | sent alert email to contact@codenghiemtuc.vn
// error | the world has already ended due to zombies!
func TestLoggerChain(t *testing.T) {
logger := NewLogger()
expect := "haha"
logger.Log(Error, expect)
// check console output
// check email is sent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment