github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/23_proto_actor/setbehavior/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	console "github.com/AsynkronIT/goconsole"
     7  	"github.com/AsynkronIT/protoactor-go/actor"
     8  )
     9  
    10  type Hello struct{ Who string }
    11  type SetBehaviorActor struct {
    12  	behavior actor.Behavior
    13  }
    14  
    15  func (state *SetBehaviorActor) Receive(context actor.Context) {
    16  	state.behavior.Receive(context)
    17  }
    18  
    19  func (state *SetBehaviorActor) One(context actor.Context) {
    20  	switch msg := context.Message().(type) {
    21  	case Hello:
    22  		fmt.Printf("Hello %v\n", msg.Who)
    23  		state.behavior.BecomeStacked(state.Other)
    24  	}
    25  }
    26  
    27  func (state *SetBehaviorActor) Other(context actor.Context) {
    28  	switch msg := context.Message().(type) {
    29  	case Hello:
    30  		fmt.Printf("%v, ey we are now handling messages in another behavior\n", msg.Who)
    31  		state.behavior.UnbecomeStacked()
    32  	}
    33  }
    34  
    35  func NewSetBehaviorActor() actor.Actor {
    36  	act := &SetBehaviorActor{
    37  		behavior: actor.NewBehavior(),
    38  	}
    39  	act.behavior.Become(act.One)
    40  	return act
    41  }
    42  
    43  func main() {
    44  	rootContext := actor.EmptyRootContext
    45  	props := actor.PropsFromProducer(NewSetBehaviorActor)
    46  	pid := rootContext.Spawn(props)
    47  	rootContext.Send(pid, Hello{Who: "Roger1"})
    48  	rootContext.Send(pid, Hello{Who: "Roger2"})
    49  	rootContext.Send(pid, Hello{Who: "Roger3"})
    50  	console.ReadLine()
    51  }