package westworldwithmessaging import ( "fmt" "math/rand" "sync" ) // doHousework is Elsa's everyday default state - the singleton // pattern is the same one used throughout this package. type doHousework struct{} var ( doHouseworkInstance *doHousework doHouseworkOnce sync.Once ) // DoHousework is the Go stand-in for "DoHousework::Instance()". func DoHousework() *doHousework { doHouseworkOnce.Do(func() { doHouseworkInstance = &doHousework{} }) return doHouseworkInstance } var _ State[Elsa] = (*doHousework)(nil) // chores is our own small stand-in for the book's actual chore list // - its sample output shows three examples ("Moppin' the floor", // "Makin' the bed", "Washin' the dishes"), so that's exactly what's // reused here. One gets picked at random each tick. var chores = []string{ "Moppin' the floor", "Makin' the bed", "Washin' the dishes", } // Enter announces that Elsa is back to her ordinary routine. A // sample run of the book's program shows this line printed right // after she finishes cooking and switches back to this state - an // earlier, more abridged sample output we saw didn't show this line // after a bathroom-break revert, but that sample was explicitly // described as just "a sample," not a complete transcript, so this // message firing every time Enter runs (bathroom revert included) // isn't a contradiction. func (s *doHousework) Enter(e *Elsa) { fmt.Printf("\n%s: Time to do some more housework!", GetNameOfEntity(e.ID())) } // Execute announces one randomly chosen chore per tick. func (s *doHousework) Execute(e *Elsa) { fmt.Printf("\n%s: %s", GetNameOfEntity(e.ID()), chores[rand.Intn(len(chores))]) } // Exit does nothing - no sample output ever shows a message here. func (s *doHousework) Exit(e *Elsa) {} // OnMessage is required now that State[T] includes it, so that every // state satisfies the interface. This state doesn't do anything // special with messages yet - false means "I didn't handle it," // which lets StateMachine.HandleMessage fall through and try the // global state instead. func (s *doHousework) OnMessage(e *Elsa, msg Telegram) bool { return false }