It’s important to distinguish here between single instances and the Singleton design pattern.
Single instances are simply a reality. Most apps are only designed to work with one configuration at a time, one UI at a time, one file system at a time, and so on. If there’s a lot of state or data to be maintained, then certainly you would want to have just one instance and keep it alive as long as possible.
The Singleton design pattern is a very specific type of single instance, specifically one that is:
- Accessible via a global, static instance field;
- Created either on program initialization or upon first access;
- No public constructor (cannot instantiate directly);
- Never explicitly freed (implicitly freed on program termination).
It is because of this specific design choice that the pattern introduces several potential long-term problems:
- Inability to use abstract or interface classes;
- Inability to subclass;
- High coupling across the application (difficult to modify);
- Difficult to test (can’t fake/mock in unit tests);
- Difficult to parallelize in the case of mutable state (requires extensive locking);
- and so on.
None of these symptoms are actually endemic to single instances, just the Singleton pattern.
What can you do instead? Simply don’t use the Singleton pattern.
Quoting from the question:
The idea was to have this one place in the app which keeps the data stored and synced, and then any new screens that are opened can just query most of what they need from there, without making repetitive requests for various supporting data from the server. Constantly requesting to the server would take too much bandwidth – and I’m talking thousands of dollars extra Internet bills per week, so that was unacceptable.
This concept has a name, as you sort of hint at but sound uncertain of. It’s called a cache. If you want to get fancy you can call it an “offline cache” or just an offline copy of remote data.
A cache does not need to be a singleton. It may need to be a single instance if you want to avoid fetching the same data for multiple cache instances; but that does not mean you actually have to expose everything to everyone.
The first thing I’d do is separate out the different functional areas of the cache into separate interfaces. For example, let’s say you were making the world’s worst YouTube clone based on Microsoft Access:
MSAccessCache ▲ | +-----------------+-----------------+ | | | IMediaCache IProfileCache IPageCache | | | | | | VideoPage MyAccountPage MostPopularPage
Here you have several interfaces describing the specific types of data a particular class might need access to – media, user profiles, and static pages (like the front page). All of that is implemented by one mega-cache, but you design your individual classes to accept the interfaces instead, so they don’t care what kind of an instance they have. You initialize the physical instance once, when your program starts, and then just start passing around the instances (cast to a particular interface type) via constructors and public properties.
This is called Dependency Injection, by the way; you don’t need to use Spring or any special IoC container, just so long as your general class design accepts its dependencies from the caller instead of instantiating them on its own or referencing global state.
Why should you use the interface-based design? Three reasons:
It makes the code easier to read; you can clearly understand from the interfaces exactly what data the dependent classes depend on.
If and when you realize that Microsoft Access wasn’t the best choice for a data back-end, you can replace it with something better – let’s say SQL Server.
If and when you realize that SQL Server isn’t the best choice for media specifically, you can break up your implementation without affecting any other part of the system. That is where the real power of abstraction comes in.
If you want to take it one step further then you can use an IoC container (DI framework) like Spring (Java) or Unity (.NET). Almost every DI framework will do its own lifetime management and specifically allow you to define a particular service as a single instance (often calling it “singleton”, but that’s only for familiarity). Basically these frameworks save you most of the monkey work of manually passing around instances, but they are not strictly necessary. You do not need any special tools in order to implement this design.
For the sake of completeness, I should point out that the design above is really not ideal either. When you are dealing with a cache (as you are), you should actually have an entirely separate layer. In other words, a design like this one:
+--IMediaRepository | Cache (Generic)---------------+--IProfileRepository ▲ | | +--IPageRepository +-----------------+-----------------+ | | | IMediaCache IProfileCache IPageCache | | | | | | VideoPage MyAccountPage MostPopularPage
The benefit of this is that you never even need to break up your
Cache instance if you decide to refactor; you can change how Media is stored simply by feeding it an alternate implementation of
IMediaRepository. If you think about how this fits together, you will see that it still only ever creates one physical instance of a cache, so you never need to be fetching the same data twice.
None of this is to say that every single piece of software in the world needs to be architected to these exacting standards of high cohesion and loose coupling; it depends on the size and scope of the project, your team, your budget, deadlines, etc. But if you’re asking what the best design is (to use in place of a singleton), then this is it.
P.S. As others have stated, it’s probably not the best idea for the dependent classes to be aware that they are using a cache – that is an implementation detail they simply should never care about. That being said, the overall architecture would still look very similar to what’s pictured above, you just wouldn’t refer to the individual interfaces as Caches. Instead you’d name them Services or something similar.
In the case you give, it sounds like the use of a Singleton is not the problem, but the symptom of a problem – a larger, architectural problem.
Why are the screens querying the cache object for data? Caching should be transparent to the client. There should be an appropriate abstraction for providing the data, and the implementation of that abstraction might utilize caching.
The issue is likely that dependencies between parts of the system are not set up correctly, and this is probably systemic.
Why do the screens need to have knowledge of where they get their data? Why are the screens not provided with an object that can fulfill their requests for data (behind which a cache is hidden)? Oftentimes the responsibility for creating screens is not centralized, and so there is no clear point of injecting the dependencies.
Again, we are looking at large-scale architectural and design issues.
Also, it is very important to understand that the lifetime of an object can be completely divorced from how the object is found for use.
A cache will have to live throughout the application’s lifetime (to be useful), so that object’s lifetime is that of a Singleton.
But the problem with Singleton (at least the common implementation of Singleton as a static class/property), is how other classes that use it go about finding it.
With a static Singleton implementation, the convention is to simply use it wherever needed. But that completely hides the dependency and tightly couples the two classes.
If we provide the dependency to the class, that dependency is explicit and all the consuming class needs to have knowledge of is the contract available for it to use.
I wrote a whole chapter on just this question. Mostly in the context of games, but most of it should apply outside of games.
The Gang of Four Singleton pattern does two things: give you convenience access to an object from anywhere, and ensure that only one instance of it can be created. 99% of the time, all you care about is the first half of that, and carting along the second half to get it adds unnecessary limitation.
Not only that, but there are better solutions for giving convenient access. Making an object global is the nuclear option for solving that, and makes it way to easy to destroy your encapsulation. Everything that’s bad about globals applies completely to singletons.
If you’re using it just because you have a lot of places in code that need to touch the same object, try to find a better way to give it to just those objects without exposing it to the entire codebase. Other solutions:
Ditch it entirely. I’ve seen lots of singleton classes that don’t have any state and are just bags of helper functions. Those don’t need an instance at all. Just make them static functions, or move them into one of the classes that the function takes as an argument. You wouldn’t need a special
Mathclass if you could just do
Pass it around. The simple solution if a method needs some other object is to just pass it in. There’s nothing wrong with passing some objects around.
Put it in the base class. If you have a lot of classes that all need access to some special object, and they share a base class, you can make that object a member on the base. When you construct it, pass in the object. Now the derived objects can all get it when they need it. If you make it protected, you ensure the object still stays encapsulated.