I am writing a client which has support of 'offline mode'. When offline records can be stored locally.
When we go online we want to be able to synchronize these records with the remote API.
I want to be able to keep track of some state like the progress of the sync, whether we're syncing or not and other things like that.
I'm considering creating a singleton manager class that can store this state but I feel like there is a better way to do this. I want to stay away from singletons as much as possible due to their global nature.
1 Answer 1
Singletons exist in programming. A lot. People don't think about this often, yet they are there. While there is some merit to avoiding "global" values, it is detrimental to avoid global designs when they are warranted.
With a singleton design, you can make sure that multiple writes to the same record won't clobber data, that reads and writes to the queue don't leave it in an unpredictable state because of non-atomic updates, and so you can answer questions like "how many records are left?" in an easy and predictable manner.
True, there are other solutions to all these problems. For example, you could create pools that hold records to sync, and put atomic locks on those methods, and so on. You'll still need a place to keep track of these pools to answer questions like above, so there's little benefit in that case.
If you had a ton of traffic on the client, it might make sense to go with a parallel/concurrent design. I doubt that's the case, but there's compelling reasons you'd want to spilt the load, perhaps so you could sync with more threads or service many records at once.
Internally, the singleton might utilize threads or other techniques, but outside calls into the manager shouldn't be as concerned with implementation details, so a singleton will also decouple your others classes a bit from the sync process.
Manager.getInstance()
to obtain a reference to the singleton?