This is a bit of weird scenario. I had a class that was quickly becoming a God class. It was doing WAY too much. Suddenly I had violated SRP. The class was responsible for X and Y and Z, oh and A, and B, don't forget C. So I decided to refactor it. The reason it got this big is because the class does a lot of work with a collection which I have done a lot of work to synchronize the access to it because it is a multi-threaded system using ReaderWriterLockSlim.
So I identified the main responsibilities. There is a part that feeds the collection. Occasionally it might need to make a new element in the collection. I have an object that cleans out the collection on a timer. So when the timer elapses I look for elements that can be removed from the collection. Then I have an object which needs to fetch stuff from the collection. It needs to ask each item in the collection for stuff so it needs to iterate.
Previously the object was doing all of this itself. Easy to manage in terms of locking. Not so easy to Unit test. Too much going on, too much mocking. It was just nasty. Breaking it out into parts makes unit testing much easier BUT it makes the locking much harder.
So each part, the feeder, the cleaner and the retriever all need an instance of this object. So I should inject it in the constructor and then I can mock it out and testing is easy. But now because the collection is shared amongst many objects I cannot give each one direct access to it. I need to provide a sort of synchronization wrapper.
I was thinking that when the feeder asks for a new item in the collection, the wrapper locks the collection, creates a new item, gives it to the feeder and notifies the cleaner that there is a new item in the collection. The cleaner adds that item to its copy of the collection.
When the cleaner runs, it runs through its version of the collection, when it finds something that can be removed it removes it from its collection and informs the wrapper and the wrapper notifies the feeder who takes it out of his collection. The retriever uses a foreach loop. So the wrapper can implement IEnumerator and IDispose. Then when the enumerator is created I can lock the collection and when it is disposed I can exit the lock.
- Is there a design pattern for what I am trying to do?
- Is there a better way to do this?
- What is a good name for this wrapper?
I thought of the following:
- Provider (But it does more than just provide)
- Maintainer (A bit vague)
- Synchronizer (I like this one the most)