Home | History | Annotate | Download | only in internal
      1 package com.xtremelabs.robolectric.internal;
      2 
      3 import android.app.Application;
      4 import android.content.Context;
      5 import com.xtremelabs.robolectric.shadows.ShadowApplication;
      6 
      7 import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
      8 import static com.xtremelabs.robolectric.Robolectric.shadowOf;
      9 
     10 public abstract class AppSingletonizer<T> {
     11     private Class<T> clazz;
     12 
     13     public AppSingletonizer(Class<T> clazz) {
     14         this.clazz = clazz;
     15     }
     16 
     17     synchronized public T getInstance(Context context) {
     18         Application applicationContext = (Application) context.getApplicationContext();
     19         ShadowApplication shadowApplication = (ShadowApplication) shadowOf(applicationContext);
     20         T instance = get(shadowApplication);
     21         if (instance == null) {
     22             instance = createInstance(applicationContext);
     23             set(shadowApplication, instance);
     24         }
     25         return instance;
     26     }
     27 
     28     protected abstract T get(ShadowApplication shadowApplication);
     29 
     30     protected abstract void set(ShadowApplication shadowApplication, T instance);
     31 
     32     protected T createInstance(Application applicationContext) {
     33         return newInstanceOf(clazz);
     34     }
     35 }
     36