Using singleton for caching

I recently read that singleton is an anti-pattern and should not be used if it is not really needed.
In all our projects, we use the singleton template to store 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 for storing this data (static class or something else)?

+6
source share
2 answers

Well, you can think of the cache as a dependency - and pass the instance (possibly the same instance) to whatever you need. This is what I would do in a situation where I already used dependency injection.

This will make it easier to test those classes that need a cache - you can create a new cache for each test and not worry about clearing the existing one. You can also parallelize tests without worrying about two tests that have ruined each other's secrets. In addition, it makes the use of the cache more understandable.

(Regardless of whether you use the interface to represent the cache, since cdhowie offers are up to you, you donโ€™t have to do this, although you would separate the classes from your dependencies more if you did. If your cache is very simple and you donโ€™t mind using production implementation in tests, maybe you should not extract the interface.)

+5
source

You would create some ICache interface that defines the members needed for the cache provider. Then you must let the instance pass to SomeClass() . You can still use the default instance (implementation of ICache ) if the caller does not specify it. This is a dependency injection pattern, which is essentially the exact opposite of a singleton pattern.

This will replace another caching mechanism (or just different cache instances) without any changes to SomeClass .

+2
source

Source: https://habr.com/ru/post/896066/


All Articles