Singleton shell for context

I am considering creating a singleton wrapper for Context, so my model objects, if necessary, can open and read from a database connection. My model objects do not have access to Context, and I would like you to not have to pass the link to the object Contextfrom object to object.

I planned to place a link to Contextreturned on this singlet Application.getApplicationContext(). This singleton object will be initialized in my user instance Applicationbefore anything else is needed or able to use it.

Can anyone think of a reason not to do this?

+3
source share
3 answers

, , :

public class MyApp extends Application {

private static MyApp instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        // ...
    }

    public static MyApp getInstance(){
        return instance;
    }

    // misc helper methods
}
0

, , .

. , :

  • .
  • - .
  • , . ?
  • .

, , , : factory , .

+2

Paste here to save formatting.

public class ContextContainer
{
    private static boolean initialized;
    private static Context context;

    private ContextContainer()
    {
        //
    }

    public static synchronized void setApplicationContext(Context context)
    {
        if (!initialized) {
            ContextContainer.context = context;
            initialized = true;
        } else {
            throw new RuntimeException("ApplicationContext has already been set!");
        }
    }

    public static synchronized Context getApplicationContext()
    {
        return context;
    }
}
0
source

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


All Articles