Dispose pattern

Uses your system voice; voice and rate in settings.

Snapshot

≈ 4 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method – usually called close , dispose , free , release depending on the language – which releases any resources the object is holding onto. Many programming languages offer language constructs to avoid having to call the dispose method explicitly in common situations. The dispose pattern is primarily used in languages whose runtime environment have automatic garbage collection (see motivation below).

In object-oriented programming, the dispose pattern is a design pattern for resource management. In this pattern, a resource is held by an object, and released by calling a conventional method – usually called close , dispose , free , release depending on the language – which releases any resources the object is holding onto. Many programming languages offer language constructs to avoid having to call the dispose method explicitly in common situations. The dispose pattern is primarily used in languages whose runtime environment have automatic garbage collection (see motivation below). include FILE* f = fopen(filename, mode); // Do something with f. fclose(f); Note that fclose is a function with a FILE* parameter. In object-oriented programming, this is instead an instance method on a file object, as in Python: from typing import TextIO f: TextIO = open(filename) Do something with f. f.close() This is precisely the dispose pattern, and only differs in syntax and code structure from traditional file opening and closing. Other resources can be managed in exactly the same way: being acquired in a constructor or factory, and released by an explicit close or dispose method. from typing import Any, TextIO def func(filename: str) -> Any: f = open(filename) if a: return x f.close() return y If the function returns at the first return, the file is never closed and the resource is leaked. from typing import TextIO def func(filename: str) -> None: f: TextIO = open(filename) g(f) # Do something with f that may raise an exception. f.close() If the intervening code raises an exception, the function exits early and the file is never closed, so the resource is leaked. Both of these can be handled by a try...finally construct, which ensures that the finally clause is always executed on exit: from typing import TextIO def func(filename: str) -> None: try: f: TextIO = open(filename) # Do something. finally: f.close() More generically: Resource resource = getResource(); try { // Resource has been acquired; perform actions with the resource. ... } finally { // Release resource, even if an exception was thrown. resource.dispose(); } The try...finally construct is necessary for proper exception safety, since the finally block enables execution of cleanup logic regardless of if an exception is thrown or not in the try block. One disadvantage of this approach is that it requires the programmer to explicitly add cleanup code in a finally block. This leads to code size bloat, and failure to do so will lead to resource leakage in the program. using (Resource resource = GetResource()) { // Perform actions with the resource. // ... } which is equal to: using System; Resource resource = GetResource() try { // Perform actions with the resource. // ... } finally { // Resource might not been acquired, or already freed if (resource != null) { ((IDisposable)resource).Dispose(); } } Similarly, the Python language has a with statement that can be used to similar effect with a context manager object. The context manager protocol requires implementing __enter__ and __exit__ methods which get automatically called by the with statement construct, to prevent duplication of code that would otherwise occur with the try / finally pattern. with resource_context_manager() as resource: # Perform actions with the resource. ... Perform other actions where the resource is guaranteed to be deallocated. ... The Java language introduced a new syntax called try -with-resources in Java version 7. It can be used on objects that implement the java.lang.AutoCloseable interface (that defines method close() ): import java.io.IOException; import java.io.OutputStream; try (OutputStream config = new OutputStream("configs/config.txt")) { // Do something with 'config' } catch (IOException e) { // Handle exception // The resource 'config' is automatically closed } In Rust, drop semantics are done using a trait std::ops::Drop , which will automatically destroy the object after leaving scope. It can be manually called by std::mem::drop() . ==Notes== ==References== ==Further reading== Microsoft Developer Network: Dispose Pattern

Text derived from https://en.wikipedia.org/w/index.php?oldid=1352535570 under CC BY-SA 4.0; modifications have been made.