Context Object Pattern

Problem

You want to avoid using protocol-specific system information outside of its relevant context.

An application typically uses system information, such as request, configuration, and security data, throughout the lifecycle of a request and response. Aspects of this system information are accessed based on their relevance to a certain processing context. When application-specific components and services are exposed to system information that is outside their context, flexibility and reusability of these components are reduced. Using a protocol-specific API outside its relevant context means exposing all the components that use this API to specific interface and parsing details. Each client component is then tightly coupled with that specific protocol.

 

Solution

Use a Context Object to encapsulate state in a protocol-independent way to be shared throughout your application.

Encapsulating system data in a Context Object, as shown in Figure 5, allows it to be shared with other parts of the application without coupling the application to a specific protocol. For example, an HTTP request parameter exists for each field of an HTML form and a Context Object can store this data in a protocol-independent manner while facilitating its conversion and validation. Then other parts of the application simply access the information in the Context Object, without any knowledge of the HTTP protocol. Any changes in the protocol are handled by the Context Object, and no other parts of the application need to change.


Figure 5: Context Object -- Class Diagram

 

Consequences

In the Business Tier, one of the additional patterns added to the catalog for the 2nd edition of our book is Application Service, which addresses problems that arise with common business logic. Adding this common logic to Session Fašades often results in the duplication of code, while encapsulating this logic within Business Objects may result in object bloat.