Middle
What is a decorator? Tell about the Decorator pattern.
sobes.tech AI
Answer from AI
A decorator is a structural design pattern that allows you to add new functionality to objects dynamically by wrapping them in other decorator objects without changing the original code.
The Decorator pattern is useful when you need to extend the behavior of an object without creating numerous subclasses.
Example in Go:
package main
import "fmt"
type Notifier interface {
Notify(message string)
}
type EmailNotifier struct {}
func (e *EmailNotifier) Notify(message string) {
fmt.Println("Email notification:", message)
}
type SMSDecorator struct {
wrapped Notifier
}
func (s *SMSDecorator) Notify(message string) {
s.wrapped.Notify(message) // basic notification
fmt.Println("SMS notification:", message) // additional behavior
}
func main() {
var notifier Notifier = &EmailNotifier{}
notifier = &SMSDecorator{wrapped: notifier}
notifier.Notify("Hello!")
}
Here, SMSDecorator adds SMS sending to the email notification without changing the EmailNotifier code.