我对Akka很新,并试图了解如何处理依赖注入。我遇到了这个examle,它引导我进入Akka扩展,现在我试图理解它与简单的静态方法调用有何不同。有关扩展的Akka教程部分就是这样的例子:
public class CountExtensionImpl implements Extension {
private final AtomicLong counter = new AtomicLong(0);
public long increment() {
return counter.incrementAndGet();
}
}
public class CountExtension extends AbstractExtensionId<CountExtensionImpl> implements ExtensionIdProvider {
public static final CountExtension EXTENSION = new CountExtension();
private CountExtension() {
}
@Override
public CountExtensionImpl createExtension(ExtendedActorSystem system) {
return new CountExtensionImpl();
}
@Override
public ExtensionId<? extends Extension> lookup() {
return EXTENSION;
}
}
public class MyActor extends UntypedActor{
@Override
public void onReceive(Object message) throws Exception {
System.out.println(CountExtension.EXTENSION.get(getContext().system()).increment());
}
}
但是我无法理解简单的单例或静态方法有什么优势? E.g。
public class MyActor extends UntypedActor{
@Override
public void onReceive(Object message) throws Exception {
Counter.increment();
}
}
答案 0 :(得分:6)
Akka扩展绑定到ActorSystem,因此是每个系统的单例而不是全局单例。