1

有人能给我解释一下吗。这是一些场景。

假设我有一个类模板并在应用程序中使用 Gin/Guice。

@Singleton
public class Template extends Compose
{
private HorizontalPanel header;
private HorizontalPanel content;
private VerticalPanel menu;

    public Template()
    {
      this.add(initHeader());
      this.add(initMenu());
      this.add(initContent());
    }

    public void setContent(Widget widget)
    {
      content.clear();
      content.add(widget);
    }
    .............
    ......
    }

并且在入门级

........
public void onModuleLoad()
{

RootPanel.get().add(new Template());
....
}

每次我需要重新加载我做的内容..

例如

HorizontalPanel hp = new HorizontalPanel();
hp.add ....
...

Template template = injector.getTemplate(); // return singleton instance using gin
template.setContent(hp)

等等..

所以,模板是单例的,据我所知,单例实例是每个 VM 一个,意思是由整个应用程序共享,对吗?模板类具有标题、菜单和内容,其想法是仅重新加载内容部分作为清理和添加小部件。但这是一个好方法吗?

例如,我们会不会出现用户“A” setContent(widgetA) 的情况,但同时用户“B”使用方法 setContent(widgetB) ,那么这里会发生什么?

谢谢,如果有人最终可以与我分享一个好方法并发表评论。

问候

4

3 回答 3

12

@Singleton is scoped to the Ginjector instance (yes, if you GWT.create() your GInjector twice, you'll get two "singletons"). There's no single mean GIN can somehow "intercept" your new Template() in onModuleLoad, so injector.getTemplate() will return a distinct template instance. (this is totally different from the "singleton code anti-pattern" that Stein talks about, using static state)

There's no magic: GIN is a code generator, it only writes code that you could have typed by hand.

As for your other questions:

  • You client code obviously run on the client, i.e. on the browser. There's one "application instance" per browser tab/window displaying your app. There's no "user A" and "user B" at the same time.
  • JavaScript is single-threaded, so you don't have to fear for concurrent accesses either.
于 2011-06-17T09:25:11.770 回答
1

我已经为我们的应用程序注入了通用 RPC 代码的类。就是这样:

@Singleton
public class SomeService {

/** The real service. */
private static final RealServiceAsync realService;

...

}

我们的杜松子酒模块:

public class MyGinModule extends AbstractGinModule {

    @Override
    protected void configure() {
        bind( SomeService .class ).in(Singleton.class);
        ...
        ...
    }

}

它作为单例注入如下:

public class ApplicationInfoPresenter {

@Inject
private SomeService service;

...
...

}
于 2011-06-17T11:35:57.180 回答
0

我很确定 GWT 编译器会忽略注释。

当我在 gwt 中需要一个 Singleton 时,我只需创建一个具有私有/受保护构造函数的类,以及一个private static NameOfSingletonClass instance;getInstance()null 时初始化实例并返回实例的方法。

于 2011-06-17T07:22:40.017 回答