Skip to content

Instantly share code, notes, and snippets.

Created January 25, 2016 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4aeaff173ce454a621d5 to your computer and use it in GitHub Desktop.
Save anonymous/4aeaff173ce454a621d5 to your computer and use it in GitHub Desktop.
Java Singleton
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