How to use @Singleton Guice?

I need to make one instance of a class - and this one instance should be accessible from anywhere in the code.

So, I found Guice ... and I want to use "@Singleton" from this package, but I do not find a single example, nor any document, how to use it and how to make an announcement.

+4
source share
3 answers

Well, My answer is not specific to @Singleton of Guice , but if you want to create a class that is accessible in all your actions, then I think you should use the Android Application . (This is my personal opinion about your need)

The way to do this is to create your own subclass of android.app.Application , and then specify the class in the application tag in your manifest . Now Android will automatically instantiate this class and make it available to your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides the getApplication() method, which has the same effect):

 class MyApp extends Application { private String myState; public String getState(){ return myState; } public void setState(String s){ myState = s; } } class Blah extends Activity { @Override public void onCreate(Bundle b){ ... MyApp appState = ((MyApp)getApplicationContext()); String state = appState.getState(); ... } } 

This has the same effect as a static variable or singleton, but integrates pretty well into the existing Android platform. Note that this will not work in all processes (should your application be one of the rare ones that has several processes).

Here is a good tutorial on how to use it, Android app class extension and working with Singleton

+4
source

@Singleton is very easy to use. It is just that.

 @Singleton public class A { @Inject public A() { } } 

Note that the single-point signal is one per injector, not a VM. Singleton is a type of scope, and GUICE also allows you to configure scopes that can be very useful. See the links below.

When you use this in another class, you just need to enter it.

 public class B { @Inject public B(A a) { } } 

http://code.google.com/p/google-guice/wiki/Scopes

http://code.google.com/p/google-guice/wiki/GettingStarted

+7
source
 public class DestinationViewManger { private static final DestinationViewManger instance = new DestinationViewManger(); public Boolean flag=false; // Private constructor prevents instantiation from other classes private DestinationViewManger(){ } public static DestinationViewManger getInstance() { return instance; } } 

// Try this singleton class once. no need for getter and setter methods

 DestinationViewManger dstv; dstv=DestinationViewManger.getInstance(); dstv.flag=true; //set the value for your flag boolean whatFlagboo=dstv.flag; //get your flag wherever you want 
+1
source

Source: https://habr.com/ru/post/1386098/


All Articles