I recently read that singleton is an anti-pattern and should not be used unless it is really needed.
In all of our projects we use the singleton pattern to hold some cache data, For example:
class SomeClass
{
public SomeClass()
{
var somedata = Singleton.Instance.GetSomeData(stringRepresintation); // or like that
var someData = Singleton.Instance.SomeData;
}
}
What is the recommended design to hold that data (static class, or something else)?
Well, you could think of the cache as a dependency - and pass an instance (probably the same instance) into everything which needed it. That's what I'd do in a situation where I was already using dependency injection.
That would make it easier to test those classes which need the cache - you could create a new cache for each test, and not have to worry about clearing out an existing one. You could also parallelize tests without worrying about two tests messing up each others caches. Additionally, it makes the cache dependency clearer.
(Whether or not you use an interface to represent the cache as cdhowie suggests is up to you. You don't have to, although it would decouple the classes from their dependencies more if you did. If your cache is very simple and you don't mind using the production implementation in tests, it may not be worth extracting an interface.)
You would create some ICache
interface that defines the members necessary for a cache provider. Then you would allow an instance to be passed in to SomeClass()
. You can still use a default instance (implementing ICache
) if the caller doesn't specify one. This is the dependency injection pattern, which is essentially the complete opposite of the singleton pattern.
This will allow a different caching mechanism (or just different cache instances) to be substituted in without any changes to SomeClass
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With