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).
Wrapping resources in objects is the object-oriented form of encapsulation, and underlies the dispose pattern.
Resources are typically represented by handles (abstract references), concretely usually integers, which are used to communicate with an external system that provides the resource. For example, files are provided by the operating system (specifically the ), which in many systems represents open files with a (an integer representing the file).
These handles can be used directly, by storing the value in a variable and passing it as an argument to functions that use the resource. However, it is frequently useful to abstract from the handle itself (for example, if different operating systems represent files differently), and to store additional auxiliary data with the handle, so handles can be stored as a field in a record, along with other data; if this in an opaque data type, then this provides information hiding and the user is abstracted from the actual representation.
For example, in , files are represented by objects of the FILE type (confusingly called "s": these are a language-level abstraction), which stores an (operating system) handle to the file (such as a ), together with auxiliary information like I/O mode (reading, writing) and position in the stream. These objects are created by calling (in object-oriented terms, a constructor), which acquires the resource and returns a pointer to it; the resource is released by calling on a pointer to the FILE object.