Reputation: 414
Could some explain me something. Here is some scenario.
Let assume i have a class template and use Gin/Guice in the app.
@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);
}
.............
......
}
and in the entry class
........
public void onModuleLoad()
{
RootPanel.get().add(new Template());
....
}
Every time i need to reload the content i do..
For example
HorizontalPanel hp = new HorizontalPanel();
hp.add ....
...
Template template = injector.getTemplate(); // return singleton instance using gin
template.setContent(hp)
and so on..
So, Template is singleton and as far as i know singleton instance is one per VM meaning shared by entire application, right? Template class has header, menu and content, the idea is to reload only the content part as cleaning and adding widgets. But is this a good approach?
For example, could we have a situation like user "A" setContent(widgetA) ,but in the same time user "B" use method setContent(widgetB) ,so what is going to happen here?
Thanks, if anyone could share with me a good approach eventually and comment that one.
Regards
Upvotes: 1
Views: 7220
Reputation: 91
I have injected the class with common RPC code for our app. Here's how:
@Singleton
public class SomeService {
/** The real service. */
private static final RealServiceAsync realService;
...
}
Our Gin module:
public class MyGinModule extends AbstractGinModule {
@Override
protected void configure() {
bind( SomeService .class ).in(Singleton.class);
...
...
}
}
And it's injected as singleton as follows:
public class ApplicationInfoPresenter {
@Inject
private SomeService service;
...
...
}
Upvotes: 1
Reputation: 64541
@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:
Upvotes: 12
Reputation: 5119
I'm pretty sure the annotation is ignored by the GWT compiler.
When I need a Singleton in gwt i just create a class with a private/protected constructor, and a private static NameOfSingletonClass instance;
and a getInstance()
method that initializes the instance if null and returns the instance.
Upvotes: 0