简体   繁体   中英

Giving my class a static getInstance(Context)

Say I have a class that wants to provide instances of itself via a static method. The instances require the use of a Context , so the method will be called like this:

Foo foo = Foo.getInstance(context);

I'm thinking of doing it like this:

public class Foo {
    private static final Map<Context, Foo> instances = new WeakHashMap<>();
    private final WeakReference<Context> weakContext;

    private Foo(Context context) {
        if(context == null) throw new NullPointerException();
        weakContext = new WeakReference<Context>(context);
    }

    public static Foo getInstance(Context context) {
        Foo instance = instances.get(context);
        if(instance == null) {
            instance = new Foo(context);
            instances.put(context, instance);
        }
        return instance;
    }
}

First of all, will this work? And second, why do I have the feeling that I'm overthinking it?

It look like you want to cache your Foo . when I need a cache I prefer it to be out of my model.

Maybe you just need a Factory and you can put the Map<Context, Foo> instances in the factory.

After thinking about it more, I'd say the code in my question is either pointlessly complicated or needs further refinement, depending on whether or not Foo needs to do something that cannot be done with the application context.

If it does, then my getInstance(...) would look similar to what I originally wrote, except that instead of Context it should require the more specific type, eg, getInstance(Activity) .

If it doesn't, then I can dispense with the Map . The instance can be a pseudo-singleton and use the application context.

This article contains a table showing what you can do with different kinds of contexts.

the situation you have described is how android system services are designed. based on the context provided, the availability and functionality of the service is determined. If you want to provide different functionalities based on context, then you could look at their implementation.

However an important point to remember would be that a context had an hierarchy too. so were you to obtain an activity context, you could also obtain the application context.

Maintaining a weak reference of context could also backfire for you:

say you had a weak reference for ActivityA , but are currently in ActivityB , you would need an ActivityB context instead now. so the usual singleton pattern should serve your purpose here. If you are trying more complicated functionality them maybe providing the use case could get you a more targeted answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM