Dispose pattern: Difference between revisions

Content deleted Content added
short description
Tags: Mobile edit Mobile app edit iOS app edit
Problems: Fix MEAN citing link
Tags: Mobile edit Mobile web edit
Line 151:
Disposal in the presence of inheritance and composition of objects that hold resources have analogous problems to destruction/finalization (via destructors or finalizers). Further, since the dispose pattern usually does not have language support for this, [[boilerplate code]] is necessary. Firstly, if a derived class overrides a <code>dispose</code> method in the base class, the overriding method in the derived class generally needs to call the <code>dispose</code> method in the base class, in order to properly release resources held in the base. Secondly, if an object has a "has a" relationship with another object that holds a resource (i.e., if an object indirectly uses a resource through another object that directly uses a resource), should the indirectly using object be disposable? This corresponds to whether the relationship is ''owning'' ([[object composition]]) or ''viewing'' ([[object aggregation]]), or even just ''communicating'' ([[association (object-oriented programming)|association]]), and both conventions are found (indirect user is responsible for the resource or is not responsible). If the indirect use is responsible for the resource, it must be disposable, and dispose the owned objects when it is disposed (analogous to destroying or finalizing owned objects).
 
Composition (owning) provides [[Encapsulation (computer programming)|encapsulation]] (only the object that is used needs to be tracked), but at the cost of considerable complexity when there are further relationships between objects, while aggregation (viewing) is considerably simpler, at the cost of lacking encapsulation. In [[.NET Framework|.NET]], convention is to only have direct user of resources be responsible: "You should implement IDisposable only if your type uses unmanaged resources directly."<ref name="idisposable">{{cite web |url=https://msdnlearn.microsoft.com/en-us/librarydotnet/fundamentals/runtime-libraries/system.-idisposable#implement-idisposable(v=vs.110).aspx |title=IDisposable Interface |accessdate=20162024-0412-0309}}</ref> See [[Resource management (computing)|resource management]] for details, and further examples.
 
== See also ==