简体   繁体   English

为什么我们在akka中将Actor和消息创建为静态类?

[英]Why we create Actors and messages in akka as static classes?

I am learning Akka and in akka docs,they have used static classes for actors and messages so I want to know why we create Actors and messages in akka as static classes.And this is what I know:- We cannot create toplevel static class and since we can create only a inner static class and a inner static class instance is not linked to a particular enclosing class instance. 我正在学习Akka和Akka文档,他们已经使用了静态类来处理actor和消息,所以我想知道为什么我们在akka中将Actor和消息创建为静态类。这就是我所知道的:-我们无法创建顶级静态类,并且因为我们只能创建内部静态类,而内部静态类实例未链接到特定的封闭类实例。 And this means multiple instances share same static class instance. 这意味着多个实例共享同一静态类实例。 So if we are creating Actors and messages static then there will be only one instance per static class. 因此,如果我们要创建Actor和静态消息,则每个静态类只有一个实例。

You don't HAVE to create the messages as static classes. 您不必将消息创建为静态类。

There are two main reasons for it: 这样做的主要原因有两个:

One is what Snickers was mentioning, ie we want to make messages immutable and it's sintactically easier to do so in Java via static classes. 一种是Snickers提到的内容,即我们希望使消息不可变,并且在Java中通过静态类在语法上更容易做到这一点。 You could do without this by setting all the fields as private and/or final, but that might make your serialization/deserialization more complicated (@JsonCreator if you are using Jackson for example...). 您可以通过将所有字段都设置为private和/或final来做到这一点,但这可能会使序列化/反序列化更加复杂(例如,如果使用的是Jackson,则@JsonCreator ...)。

The second is that my declaring the messages as inner classes of the actor that accepts them, you establish a semantical relation between the two making it easier to know what actor accepts what messages. 第二个是,我将消息声明为接受消息的参与者的内部类,因此您在两者之间建立了语义关系,从而更容易知道哪个参与者接受了什么消息。

But you can easily disregard all these suggestions and build them as normal classes and you yourself making sure that they are not modified by anyone in other ways. 但是您可以轻松地忽略所有这些建议,并将其构建为普通类,并且您自己可以确保任何人都不会以其他方式修改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM