State Machine com Type Switch


O padrão State Machine é perfeito quando um objeto pode estar em diferentes estados e seu comportamento muda conforme o estado atual. Em Go, uma forma elegante de implementá-lo é combinar interfaces com um type switch, permitindo decidir o comportamento com base no tipo concreto do estado.
switch v := state.(type) para descobrir o tipo concreto e executamos o comportamento apropriado.Neste exemplo, um pedido passa por três estados: Novo, Pago, Enviado. Cada estado implementa a interface OrderState, e o contexto Order usa um type switch para tratar cada estado de forma específica.
package main import "fmt" // OrderState define o contrato para qualquer estado do pedido. type OrderState interface { Status() string } // Estados concretos type NewState struct{} func (NewState) Status() string { return "Novo" } type PaidState struct{} func (PaidState) Status() string { return "Pago" } type ShippedState struct{} func (ShippedState) Status() string { return "Enviado" } // Contexto que mantém o estado atual type Order struct { state OrderState } func NewOrder() *Order { return &Order{state: NewState{}} } func (o *Order) SetState(state OrderState) { fmt.Println("Mudando estado para:", state.Status()) o.state = state } func (o *Order) Process() { switch state := o.state.(type) { case NewState: fmt.Println("Processando pedido novo. Verificando pagamento...") o.SetState(PaidState{}) case PaidState: fmt.Println("Pedido pago. Preparando envio...") o.SetState(ShippedState{}) case ShippedState: fmt.Println("Pedido já enviado! Nada a fazer.") default: fmt.Printf("Estado desconhecido: %T\n", state) } } func main() { order := NewOrder() order.Process() // Novo -> Pago order.Process() // Pago -> Enviado order.Process() // Enviado -> sem ação }
type switch.type switch, recursos idiomáticos da linguagem.State Machines com type switch são uma abordagem simples e poderosa em Go para variar comportamentos de acordo com o estado atual. Perfeitas para workflows, pedidos, processos de negócio e qualquer cenário em que as regras mudem conforme a fase.
The State Machine pattern shines when an object has distinct states and its behavior depends on the state it’s in. In Go, a clean way to implement this is by combining interfaces with a type switch, deciding behavior based on the concrete type.
switch v := state.(type) to determine the concrete type and perform the proper behavior.This order moves through three states: New, Paid, Shipped. Each state implements OrderState, and the Order context uses a type switch to handle them.
package main import "fmt" // OrderState defines the state contract. type OrderState interface { Status() string } // Concrete states type NewState struct{} func (NewState) Status() string { return "New" } type PaidState struct{} func (PaidState) Status() string { return "Paid" } type ShippedState struct{} func (ShippedState) Status() string { return "Shipped" } // Context holding the current state type Order struct { state OrderState } func NewOrder() *Order { return &Order{state: NewState{}} } func (o *Order) SetState(state OrderState) { fmt.Println("Switching state to:", state.Status()) o.state = state } func (o *Order) Process() { switch state := o.state.(type) { case NewState: fmt.Println("Processing new order. Checking payment...") o.SetState(PaidState{}) case PaidState: fmt.Println("Order paid. Preparing shipment...") o.SetState(ShippedState{}) case ShippedState: fmt.Println("Order already shipped! Nothing else to do.") default: fmt.Printf("Unknown state: %T\n", state) } } func main() { order := NewOrder() order.Process() // New -> Paid order.Process() // Paid -> Shipped order.Process() // Shipped -> no op }
type switch.
type switch.State Machines with type switch are a natural fit in Go when behavior shifts based on state. Perfect for workflows, order processing, or any domain where rules evolve per phase.