Behaviors就是Actor接收到消息後能夠改變處理的方法,相同的Actor,每次調用,轉到不一樣的Actor內方法執行,很是適合按流程進行的場景。Behaviors就經過在Actor內部實例化一個Behavior對象,而後經過這個對象的Become來切換執行的方法的。spa
碼友看碼:code
1 using Proto; 2 using System; 3 using System.Threading.Tasks; 4 5 namespace P007_Behaviors 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 var props = Actor.FromProducer(() => new LightBulb()); 12 var pid = Actor.Spawn(props); 13 while (true) 14 { 15 Console.WriteLine("----------------------------"); 16 Console.WriteLine("按開關"); 17 Console.ReadLine(); 18 var message = pid.RequestAsync<string>(new PressSwitch()).Result; 19 Console.WriteLine(message); 20 21 message = pid.RequestAsync<string>(new Touch()).Result; 22 Console.WriteLine(message); 23 } 24 } 25 } 26 27 public class LightBulb : IActor 28 { 29 private readonly Behavior _behavior; 30 31 public LightBulb() 32 { 33 _behavior = new Behavior(); 34 //把Off方法放入棧 35 _behavior.BecomeStacked(Off); 36 } 37 public Task ReceiveAsync(IContext context) 38 { 39 //切換到behavior指定的方法,來充當ReceiveAsync 40 return _behavior.ReceiveAsync(context); 41 } 42 /// <summary> 43 /// 關 44 /// </summary> 45 /// <param name="context"></param> 46 /// <returns></returns> 47 private Task Off(IContext context) 48 { 49 switch (context.Message) 50 { 51 case PressSwitch _: 52 context.Respond("打開"); 53 _behavior.Become(On); 54 break; 55 case Touch _: 56 context.Respond("涼的"); 57 break; 58 } 59 return Actor.Done; 60 } 61 /// <summary> 62 /// 開 63 /// </summary> 64 /// <param name="context"></param> 65 /// <returns></returns> 66 private Task On(IContext context) 67 { 68 switch (context.Message) 69 { 70 case PressSwitch _: 71 context.Respond("關閉"); 72 _behavior.Become(Off); 73 break; 74 case Touch _: 75 context.Respond("燙手"); 76 break; 77 } 78 return Actor.Done; 79 } 80 } 81 class PressSwitch 82 { } 83 class Touch 84 { } 85 86 }
幾個要點,在Actor構造中把Off放入方法棧,在Receive中調用Behavior的Receive,同時能夠按本身業務邏輯切換方法,這樣在必定程度上增長了Actor的靈活性,讓一個Actor能夠按設定流程實現不一樣行爲。對象
Behavior提供了三個切換方法相關的方法:blog
看結果:string