Created
January 8, 2026 09:59
-
-
Save Dostonlv/6780c811baa619edb9e74bc381710cca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| type State interface { | |
| Next(o *Order) | |
| Name() string | |
| } | |
| type Order struct { | |
| state State | |
| } | |
| func NewOrder() *Order { | |
| return &Order{ | |
| state: NewState{}, | |
| } | |
| } | |
| func (o *Order) Next() { | |
| o.state.Next(o) | |
| } | |
| func (o *Order) Status() string { | |
| return o.state.Name() | |
| } | |
| type NewState struct{} | |
| func (NewState) Next(o *Order) { | |
| fmt.Println("NEW -> PAID") | |
| o.state = PaidState{} | |
| } | |
| func (NewState) Name() string { | |
| return "NEW" | |
| } | |
| type PaidState struct{} | |
| func (PaidState) Next(o *Order) { | |
| fmt.Println("PAID -> SHIPPED") | |
| o.state = ShippedState{} | |
| } | |
| func (PaidState) Name() string { | |
| return "PAID" | |
| } | |
| type ShippedState struct{} | |
| func (ShippedState) Next(o *Order) { | |
| fmt.Println("SHIPPED -> DONE") | |
| o.state = DoneState{} | |
| } | |
| func (ShippedState) Name() string { | |
| return "SHIPPED" | |
| } | |
| type DoneState struct{} | |
| func (DoneState) Next(o *Order) { | |
| fmt.Println("DONE -> END (no next)") | |
| } | |
| func (DoneState) Name() string { | |
| return "DONE" | |
| } | |
| func main() { | |
| order := NewOrder() | |
| fmt.Println(order.Status()) // NEW | |
| order.Next() | |
| fmt.Println(order.Status()) // PAID | |
| order.Next() | |
| fmt.Println(order.Status()) // SHIPPED | |
| order.Next() | |
| fmt.Println(order.Status()) // DONE | |
| order.Next() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment