I’m writing a program where among lots of other stuff I need three classes we can call here writer, storage and reader.
Writer needs to access the storage class very very often while reader instead somewhat seldom especially compared to writer. Storage class is there only to store the data writer writes. The only thing the writer is doing, is just to write some short bursts of data quite often. The reader reads the written data from storage and then flushes the storage to free some space for the writer to write new data. To give some numbers and idea of the frequency of the accesses let’s say that the writer is accessing the storage numerous times in minute and the reader is accessing it approximately once in an hour.
So the question is that do I need to use the singleton pattern in the storage class or is it enough to declare it as static class?
Also how I can ensure that when the reader class is using the storage, it releases the storage resource immediately after it has read and flushed the data from the storage? Most of the time the storage class should be available for the writer to write the data in it.
The singleton approach looks nice especially that I’m not from OOP background. I’ve heard that it’s bad though.
Basically, singleton is pretty much the same as a static class. Both are bad and good in same circumstances, but singleton is more “object-orienty”. In a prototype-based language, there is no real distinction.
Singletons get a bad rep because a lot of people are using them as a replacement for global variables (which now everyone “knows” are bad). Used this way, singletons are equally bad as global variables. Use a singleton if it really models an object which you are provably certain only has one instance. If it even theoretically may have another instance in a future, or if it doesn’t model something specific, the singleton pattern should not be used – nor should a static class.
All this has nothing to do with your reader/writer problem; one is, as comments indicate, a producer/consumer pattern, or an observer pattern (depending how you implement it). The other is the basic object oriented design issue.