java - Giving my class a static getInstance(Context) -


say have class wants provide instances of via static method. instances require use of context, method called this:

foo foo = foo.getinstance(context); 

i'm thinking of doing 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, work? , second, why have feeling i'm overthinking it?

it want cache foo. when need cache prefer out of model.

maybe need factory , can put map<context, foo> instances in factory.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -