Last active
August 29, 2015 14:10
-
-
Save billmote/c983153f4486d2a0aedf to your computer and use it in GitHub Desktop.
A singleton manager class that counts on being initialized but saves the call to getInstance() from every accessor. Downside: you have static methods that rely on internal state.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class MySingletonManager { | |
| public static final String TAG = MySingletonManager.class.getSimpleName(); | |
| private static MySingletonManager mInstance; | |
| private Application mContext; | |
| private ArrayList<PickleData> mSavedPickles = new ArrayList<PickleData>(); | |
| @DebugLog | |
| private MySingletonManager() { | |
| // Don't let this class get instantiated directly. | |
| } | |
| @DebugLog | |
| private MySingletonManager(Application context) { | |
| mContext = context; | |
| } | |
| @DebugLog | |
| public static void initialize(Application context) { | |
| if (mInstance == null) { | |
| mInstance = new MySingletonManager(context); | |
| } | |
| loadSavedPickles(); | |
| } | |
| private static MySingletonManager getInstance() { | |
| if (mInstance == null) { | |
| throw new IllegalStateException("Call initialize() from your Application class with Application Context."); | |
| } | |
| return mInstance; | |
| } | |
| @DebugLog | |
| public static void setSavedPickles() { | |
| // ... | |
| PickleData pickleData; | |
| for (int i = 0; i < size; i++) { | |
| pickleData = getInstance().mSavedPickles.get(i); | |
| pickleData.setId(i); | |
| // ... | |
| } | |
| // ... | |
| } | |
| @DebugLog | |
| public static ArrayList<PickleData> getSavedPickles() { | |
| return getInstance().mSavedPickles; | |
| } | |
| @DebugLog | |
| public static void loadSavedPickles() { | |
| getInstance().mSavedPickles.clear(); | |
| // ... | |
| for (int i = 0; i < num; i++) { | |
| // ... | |
| getInstance().mSavedPickles.add(new PickleData(i, obj, getInstance().mContext)); | |
| } | |
| // ... | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment