Strategy Pattern em Go


O Strategy é um padrão comportamental que permite definir uma família de algoritmos, encapsulá-los atrás de uma interface comum e trocá-los em tempo de execução. Em vez de empilhar if/else ou switch para cada comportamento, você delega a lógica a objetos separados, deixando o código mais limpo, extensível e testável.
Go favorece interfaces pequenas, então uma função única já basta. Como o runtime não checa nil automaticamente, é comum validar a estratégia antes de usá-la para evitar panics.
type PaymentStrategy interface { Pay(amount float64) error }
type PixPayment struct{} func (PixPayment) Pay(amount float64) error { fmt.Printf("Pagando via PIX: R$ %.2f\n", amount) return nil } type CreditCardPayment struct{} func (CreditCardPayment) Pay(amount float64) error { fmt.Printf("Pagando via Cartão: R$ %.2f\n", amount) return nil } type PayPalPayment struct{} func (PayPalPayment) Pay(amount float64) error { fmt.Printf("Pagando via PayPal: R$ %.2f\n", amount) return nil }
type PaymentProcessor struct { strategy PaymentStrategy } func NewPaymentProcessor(strategy PaymentStrategy) *PaymentProcessor { return &PaymentProcessor{strategy: strategy} } func (pp *PaymentProcessor) SetStrategy(strategy PaymentStrategy) { pp.strategy = strategy } func (pp *PaymentProcessor) Process(amount float64) error { if pp.strategy == nil { return fmt.Errorf("nenhuma estratégia definida") } return pp.strategy.Pay(amount) }
func main() { processor := NewPaymentProcessor(PixPayment{}) _ = processor.Process(100.0) processor.SetStrategy(CreditCardPayment{}) _ = processor.Process(250.0) processor.SetStrategy(PayPalPayment{}) _ = processor.Process(80.0) }
Sempre que o comportamento variar, mas a operação principal for a mesma, o Strategy fornece um caminho claro para organizar o código: crie uma interface pequena, encapsule cada variação e delegue a execução ao contexto. Em Go, a implementação é direta, segura e se integra ao modo idiomático de compor objetos via interfaces.
Strategy is a behavioral pattern that allows defining a family of algorithms, encapsulating them behind a common interface, and swapping them at runtime. Instead of piling up if/else or switch for each behavior, you delegate the logic to separate objects, making the code cleaner, more extensible, and testable.
Go favors small interfaces, so a single function is enough. Since the runtime doesn't check nil automatically, it's common to validate the strategy before using it to avoid panics.
type PaymentStrategy interface { Pay(amount float64) error }
type PixPayment struct{} func (PixPayment) Pay(amount float64) error { fmt.Printf("Paying via PIX: R$ %.2f\n", amount) return nil } type CreditCardPayment struct{} func (CreditCardPayment) Pay(amount float64) error { fmt.Printf("Paying via Credit Card: R$ %.2f\n", amount) return nil } type PayPalPayment struct{} func (PayPalPayment) Pay(amount float64) error { fmt.Printf("Paying via PayPal: R$ %.2f\n", amount) return nil }
type PaymentProcessor struct { strategy PaymentStrategy } func NewPaymentProcessor(strategy PaymentStrategy) *PaymentProcessor { return &PaymentProcessor{strategy: strategy} } func (pp *PaymentProcessor) SetStrategy(strategy PaymentStrategy) { pp.strategy = strategy } func (pp *PaymentProcessor) Process(amount float64) error { if pp.strategy == nil { return fmt.Errorf("no strategy defined") } return pp.strategy.Pay(amount) }
func main() { processor := NewPaymentProcessor(PixPayment{}) _ = processor.Process(100.0) processor.SetStrategy(CreditCardPayment{}) _ = processor.Process(250.0) processor.SetStrategy(PayPalPayment{}) _ = processor.Process(80.0) }
Whenever behavior varies but the main operation is the same, Strategy provides a clear path to organize the code: create a small interface, encapsulate each variation, and delegate execution to the context. In Go, the implementation is straightforward, safe, and integrates with the idiomatic way of composing objects via interfaces.