In my project there is a document management system. There is a base Document class and some derived classes. There is also a DocumentManager class which manages the open/close/activate operations of documents.
The Document and its derived classes may want to do something upon being loaded, closed, etc, but the state change is controlled by the manager class, so currently there are (virtual) methods like OnLoaded(), OnClosed() on the Document class called by the DocumentManager class. It works fine except exposing these methods to public seems unnecessary.
An alternative design is to make DocumentManager class firing events and each Document instance subscribe to these events. IMHO it doesn’t make a big difference yet introduces the risk of memory leak.
I have a gut feeling that none of these is “the solution” and there is a best practice right for the problem. Can someone enlighten me please?
My gut feeling, though it’s difficult to be sure without knowing the specific requirements of your project, is that you’ve got logic in your
DocumentManagerclass which should probably be in the sub-classes of yourDocumentclass.I would imagine a (potentially abstract)
Documentbase class with publicload,closeandwhatevermethods. Each sub-class would implement those methods according to its specific requirements allowing you to easily create any number ofDocumentsub-classes, without the logic in theDocumentManagerneeding to change (see polymorphism). If those operations are asynchronous, yourDocumentclasses would dispatch events to inform theDocumentManagerthat they had completed.This would leave the
DocumentManagerwith the single responsibility of managing (I’m assuming) its collection ofDocumentinstances.