Created
January 25, 2016 08:19
-
-
Save anonymous/4aeaff173ce454a621d5 to your computer and use it in GitHub Desktop.
Java Singleton
This file contains 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 NotificationUtility { | |
private static NotificationUtility instance; | |
// singleton GSON object, to be used by any other class (dirty) | |
public Gson gson = new Gson(); | |
// private singleton list of notifications, to be accessed from BackgroundService | |
private static List<Notification> notifications; | |
public static NotificationUtility getInstance() { | |
return (instance == null) ? new NotificationUtility() : instance; | |
} | |
public List<Notification> getList() { | |
// Ensure read only occured if no existing list exists | |
if (notifications == null) { | |
String storedNotifs = readFromStorage(location); | |
notifications = gson.fromJson(storedNotifs, new TypeToken<List<Notification>>(){}.getType()); | |
} | |
return notifications | |
} | |
public void store(String apiResponse) { | |
NotificationUtility.notifications = gson.fromJson(apiResponse, new TypeToken<List<Notification>>(){}.getType()); | |
writeToStorage(apiResponse); | |
} | |
public void append(String socketResponse) { | |
Notification incoming = gson.fromJSON(socketResponse, Notification.class); | |
List<Notification> tempList = getList(); | |
if (tempList.contains(incoming) { | |
update(tempList); | |
} else { | |
// insert new notif to first position | |
tempList.add(0, incoming); | |
} | |
String updatedNotifs = gson.toJSON(tempList); | |
writeToStorage(updatedNotifs); | |
// Override existing global list of notifications | |
notifications = tempList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment