开发者

Singleton wrapper for Context

I'm considering creating a singleton wrapper for a Context so my model objects, if necessary, can open and read from a database connection. My model objects do not have access to a Context, and I'd like to avoid needing to pass a reference to a开发者_JS百科 Context from object to object.

I was planning to place into this singleton a reference to the Context returned by Application.getApplicationContext(). This singleton object would be initialized in my custom Application instance before anything else would need to or have a chance to use it.

Can anyone think of a reason to not do this?


I would urge you to think about what reasons you have for not passing a reference of the application context into your model objects.

There are various well-documented disadvantages of using singletons. I won't go into detail here but you might want to consider:

  • How singletons limit your ability to properly unit-test your application.
  • Singletons hide dependencies between different entities in the code- you cannot determine dependecies from inspecting the interfaces.
  • You have no real control over the lifetime of a singleton, it could exist for the lifetime of your application. Do you really want to potentially hold a DB connection for the lifetime of your app?
  • The thread safety of your singleton.

If you valid reasons for not passing a reference to a context to other parts of your application then perhaps you should consider some other pattern- a factory might be one possible solution, a service another.


I'm not sure I get your idea, but here's what's been working for me:

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
}


Pasted here to preserve 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜